Python 字符串操作
Python 字符串操作 · 难度:入门 · +10XP
Python 字符串操作
字符串(String)是Python中最常用的数据类型之一,用单引号或双引号包裹。字符串是不可变的,一旦创建就不能修改其中的单个字符。
创建字符串
# 三种创建方式
s1 = 'Hello World'
s2 = "Python 编程"
s3 = '''多行字符串
可以跨越多行
保留换行符'''
字符串索引与切片
字符串可以像列表一样通过索引访问单个字符,通过切片获取子串。
s = "Hello World"
print(s[0]) # H — 第一个字符
print(s[-1]) # d — 最后一个字符
print(s[0:5]) # Hello — 索引0到4(不含5)
print(s[6:]) # World — 从索引6到末尾
print(s[::-1]) # dlroW olleH — 反转字符串
常用字符串方法
| 方法 | 作用 | 示例 |
|---|---|---|
upper() | 全部大写 | "hello".upper() → "HELLO" |
lower() | 全部小写 | "HELLO".lower() → "hello" |
strip() | 去除两端空白 | " hi ".strip() → "hi" |
replace(old,new) | 替换子串 | "abc".replace("a","x") → "xbc" |
split(sep) | 按分隔符拆分 | "a,b,c".split(",") → ["a","b","c"] |
join(iter) | 用分隔符连接 | ",".join(["a","b"]) → "a,b" |
find(sub) | 查找子串位置 | "hello".find("e") → 1 |
startswith(pre) | 是否以...开头 | "hi.py".startswith("hi") → True |
endswith(suf) | 是否以...结尾 | "hi.py".endswith(".py") → True |
f-string 格式化(Python 3.6+)
f-string 是目前最推荐的字符串格式化方式,简洁且高效:
name = "小明"
age = 20
score = 95.5
print(f"{name}今年{age}岁,成绩{score}分")
# 输出:小明今年20岁,成绩95.5分
# 指定小数位数
print(f"平均分:{score:.1f}") # 95.5
# 表达式也可以
print(f"明年{age + 1}岁") # 明年21岁
字符串判断方法
"123".isdigit() # True — 是否全数字
"abc".isalpha() # True — 是否全字母
"a1".isalnum() # True — 是否字母或数字
" ".isspace() # True — 是否全空白
"Abc".istitle() # True — 是否标题格式
实战练习
- 输入"张三,18,北京",用split拆分成列表
- 将["Python","Java","Go"]用" | "连接成一个字符串
- 写一个函数is_palindrome(s)判断字符串是否为回文(正反读一样),如"上海自来水来自海上"
- 用f-string格式化输出:商品名、单价、数量、总价,保留两位小数