跳到主要内容

String 常用方法

类型基础介绍见 Python 数据类型。

常用方法​

方法说明示例
upper() / lower()转大写 / 转小写'Py'.upper() → 'PY'
strip()去除两端空白字符' hi '.strip() → 'hi'
split(sep)按分隔符拆分为列表'a,b,c'.split(',') → ['a', 'b', 'c']
join(iterable)用指定字符连接序列'-'.join(['a', 'b']) → 'a-b'
find(sub)查找子串,返回下标(找不到返回 -1)'abc'.find('b') → 1
replace(old, new)替换子串'a-b'.replace('-', '+') → 'a+b'
startswith() / endswith()判断前缀 / 后缀'a.py'.endswith('.py') → True
count(sub)统计子串出现次数'aaa'.count('a') → 3

字符串是不可变的:以上方法都不会修改原字符串,而是返回一个新字符串。

格式化字符串​

name, age = 'Alice', 18

# f-string(推荐,Python 3.6+)
print(f'{name} 今年 {age} 岁')

# format() 方法
print('{} 今年 {} 岁'.format(name, age))

# % 格式化(旧式)
print('%s 今年 %d 岁' % (name, age))

综合示例​

text = ' Hello, Python World '

clean = text.strip() # 'Hello, Python World'
words = clean.split() # ['Hello,', 'Python', 'World']
lower = clean.lower() # 'hello, python world'
replaced = lower.replace('python', 'java') # 'hello, java world'

print('-'.join(words)) # Hello,-Python-World

快速查看方法列表​

# 列出所有非魔法方法
str_methods = [method for method in dir(str) if not method.startswith('__')]
print("字符串方法列表:", str_methods)

# 输出某个方法的帮助
help(str.upper) # 查看 upper() 的用法