字符串
Python 字符串是不可变序列,支持索引、切片和丰富的处理方法。
常用方法
- 大小写:
upper() lower() title(); - 判断:
startswith() endswith() isdigit(); - 清理:
strip()(去首尾空白); - 查找替换:
find() replace(); - 拆分合并:
split() join(); - 格式化:f-string(推荐)、
format()、%。
f-string 是最推荐的格式化方式:f"{变量}",支持表达式和格式说明(如保留小数 :.2f)。
代码示例
text = " Hello, Python! "
print(text.strip()) # Hello, Python!
print(text.upper()) # HELLO, PYTHON!
print(text.lower().strip())
# 查找与替换
print(text.find("Python")) # 下标 9
print(text.replace("Python", "世界"))
# 拆分与合并
words = "apple,banana,orange".split(",")
print(words) # [apple, banana, orange]
print("-".join(words)) # apple-banana-orange
# 判断
print("123".isdigit()) # True
print("abc".isalpha()) # True
# f-string 格式化
name = "小王"
score = 88.567
print(f"姓名:{name},成绩:{score:.2f} 分")
print(f"面积:{3.14159 * 2 ** 2:.1f}")
# 索引与切片
s = "Python"
print(s[0], s[-1]) # P n
print(s[0:3]) # Pyt
📚 Python 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
print("hello") | 输出到控制台 |
name = "张三" | 变量赋值(无需声明类型) |
if x > 0: ... | 条件判断(注意冒号和缩进) |
for i in range(10): ... | 循环(缩进是语法的一部分) |
while x < 10: ... | 条件循环 |
def fn(a, b): return a + b | 定义函数 |
class Person: ... | 定义类 |
list = [1, 2, 3] | 列表(可改) |
tuple = (1, 2) | 元组(不可改) |
dict = {"key": "value"} | 字典(键值对) |
set = {1, 2, 3} | 集合(去重) |
len(obj) | 取长度 |
str(x) / int(x) / float(x) | 类型转换 |
s.split(",") | 字符串按分隔符拆分 |
" ".join(list) | 列表拼接成字符串 |
import os | 导入模块 |
from math import sqrt | 从模块导入指定函数 |
try: ... except Exception as e: ... | 异常捕获 |
with open("a.txt", "r") as f: ... | 文件读取(自动关闭) |
f"你好 {name}" | f-string 格式化 |
lambda x: x * 2 | 匿名函数 |
list(map(fn, arr)) | 函数式处理列表 |
range(start, stop, step) | 生成数字序列 |
if __name__ == "__main__": | 主入口判断 |
pip install 包名 | 安装第三方包(命令行) |