Day2 字符串操作与比较运算
打卡任务
- 阅读本节讲义或 Notebook
- 跑通示例代码
- 整理 3 个关键点
- 完成当日打卡输出
课程资料
- 训练营讲义:https://docs.qq.com/doc/DTFhndExSRGNHS3B6?nlc=1
- GitHub 仓库:https://github.com/cheer932041235/Python60DaysChallenge
- 本日 Notebook:Day2 字符串操作与比较运算.ipynb
Notebook 内容
DAY2 字符串与比较运算
一、变量的类型
1.1 认识变量类型
# Python 中常见的基本数据类型
name = "小明" # 字符串 (str)
age = 18 # 整数 (int)
height = 1.75 # 浮点数 (float)
is_student = True # 布尔值 (bool)
# 使用 type() 函数查看变量类型
print(f"name 的类型: {type(name)}")
print(f"age 的类型: {type(age)}")
print(f"height 的类型: {type(height)}")
print(f"is_student 的类型: {type(is_student)}")
我们再来看一下vscode的变量功能
1.2 类型转换
# 有时需要在不同类型之间转换
age = 18
age_str = str(age) # 转换为字符串
print(f"年龄是: {age_str}")
score = "95"
score_num = int(score) # 转换为整数
print(f"分数是: {score_num}")
price = "19.9"
price_float = float(price) # 转换为浮点数
print(f"价格是: {price_float}")
二、字符串操作
2.1 字符串的基本操作
str1 = "Hello"
str2 = "Python"
# 1. 字符串拼接
greeting = str1 + " " + str2
print(f"拼接结果: {greeting}")
# 2. 计算字符串长度
length = len(greeting)
print(f"字符串长度: {length}")
2.2 字符串的索引
# 3. 获取指定位置的字符
first_char = greeting[0] # 第一个字符
second_char = greeting[1] # 第二个字符
last_char = greeting[-1] # 最后一个字符
print(f"第一个字符: {first_char}")
print(f"第二个字符: {second_char}")
print(f"最后一个字符: {last_char}")
2.3 字符串的切片
核心口诀:取左不取右
text = "HelloPython"
# 切片语法: 字符串[起始位置:结束位置]
# 注意: 包含起始位置,不包含结束位置(取左不取右)
# H e l l o P y t h o n
# 0 1 2 3 4 5 6 7 8 9 10
print(f"前 5 个字符: {text[0:5]}") # Hello (索引0到4)
print(f"第 6-11 个字符: {text[5:11]}") # Python (索引5到10)
# 省略起始位置,从开头开始
print(f"前 5 个字符: {text[:5]}") # Hello
# 省略结束位置,到末尾结束
print(f"从第 6 个字符到末尾: {text[5:]}") # Python
# 同时省略,复制整个字符串
print(f"完整字符串: {text[:]}") # HelloPython
三、比较运算
# 比较运算符用于比较两个值,结果是布尔值(True 或 False)
score_a = 75
score_b = 90
# 常用比较运算符:
# > 大于
# < 小于
# >= 大于等于
# <= 小于等于
# == 等于
# != 不等于
is_a_higher = score_a > score_b # False
is_a_lower_or_equal = score_a <= score_b # True
is_equal = score_a == score_b # False
is_different = score_a != score_b # True
print(f"{score_a} > {score_b}: {is_a_higher}")
print(f"{score_a} <= {score_b}: {is_a_lower_or_equal}")
print(f"{score_a} == {score_b}: {is_equal}")
print(f"{score_a} != {score_b}: {is_different}")
同步标记:python60days-github-day-2
原创
Day2 字符串操作与比较运算
本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
评论交流
欢迎留下你的想法