当前位置:首页>python>Python 字符串常用方法详解,掌握这些方法,让你处理文本游刃有余!

Python 字符串常用方法详解,掌握这些方法,让你处理文本游刃有余!

  • 2026-10-11 08:35:28
Python 字符串常用方法详解,掌握这些方法,让你处理文本游刃有余!
【写在前面】可以参看我的视频进行学习,喜欢的话,关注点赞分享。
需要笔记代码的朋友,可以在评论区留言。

一、字符串基础操作

1. 创建字符串

s1 = 'Hello World'
s2 = "Python 字符串"
s3 = '''多行
字符串'''

2. 索引与切片

s = "Python"
print(s[0])      # P  (第一个字符)
print(s[-1])     # n  (最后一个字符)
print(s[0:3])    # Pyt (切片,左闭右开)
print(s[::2])    # Pto (步长为2)
print(s[::-1])   # nohtyP (反转字符串)

二、查找与判断

3. find() / index() — 查找子串位置

s = "hello world"
print(s.find('o'))       # 4  (首次出现位置,找不到返回-1)
print(s.find('o', 5))    # 7  (从索引5开始找)
print(s.index('o'))      # 4  (与find类似,但找不到会报错)
print(s.rfind('o'))      # 7  (从右边开始找)

4. count() — 统计出现次数

s = "banana"
print(s.count('a'))      # 3
print(s.count('na'))     # 2

5. startswith() / endswith() — 开头/结尾判断

s = "example.txt"
print(s.startswith('ex'))   # True
print(s.endswith('.txt'))   # True
print(s.endswith(('.py', '.txt')))  # True (支持元组)

6. 常用判断方法

s = "Python3"
print(s.isalpha())       # False (含数字)
print("abc".isalpha())   # True  (全是字母)
print("123".isdigit())   # True  (全是数字)
print("  ".isspace())    # True  (全是空格)
print("Title Case".istitle())  # True (首字母大写)
print("UPPER".isupper())       # True
print("lower".islower())       # True

三、字符串修改

7. replace() — 替换子串

s = "I like Java, Java is good"
print(s.replace('Java', 'Python'))
# I like Python, Python is good

print(s.replace('Java', 'Python', 1))
# I like Python, Java is good (只替换1次)

8. upper() / lower() / title() / swapcase() — 大小写转换

s = "Hello Python"
print(s.upper())      # HELLO PYTHON
print(s.lower())      # hello python
print(s.title())      # Hello Python (每个单词首字母大写)
print(s.swapcase())   # hELLO pYTHON (大小写互换)

9. strip() / lstrip() / rstrip() — 去除空白

s = "  hello world  "
print(s.strip())      # "hello world"  (两边)
print(s.lstrip())     # "hello world  " (左边)
print(s.rstrip())     # "  hello world" (右边)

# 去除指定字符
print("###Python###".strip('#'))  # Python

四、字符串分割与连接

10. split() / rsplit() — 分割字符串

s = "apple,banana,orange"
print(s.split(','))        # ['apple', 'banana', 'orange']

s2 = "a b c d e"
print(s2.split())          # ['a', 'b', 'c', 'd', 'e'] (默认按空白分割)
print(s2.split(' ', 2))    # ['a', 'b', 'c d e'] (最多分割2次)

# 按行分割
s3 = "第一行\n第二行\n第三行"
print(s3.splitlines())     # ['第一行', '第二行', '第三行']

11. join() — 连接字符串

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

# 实际应用:拼接路径
paths = ['home', 'user', 'documents']
print('/'.join(paths))     # home/user/documents

五、字符串对齐与填充

12. center() / ljust() / rjust() / zfill()

s = "Python"

print(s.center(12, '-'))   # ---Python---  (居中)
print(s.ljust(12, '*'))    # Python******  (左对齐)
print(s.rjust(12, '*'))    # ******Python  (右对齐)

# 补零(常用于编号)
print("42".zfill(5))       # 00042
print("-42".zfill(5))      # -0042

六、格式化字符串

13. % 格式化(旧式)

name = "小明"
age = 20
print("我叫%s,今年%d岁" % (name, age))

14. str.format()(推荐)

print("我叫{},今年{}岁".format("小明", 20))
print("我叫{0},今年{1}岁".format("小明", 20))
print("我叫{name},今年{age}岁".format(name="小明", age=20))

# 格式化数字
print("{:.2f}".format(3.14159))   # 3.14
print("{:,}".format(1000000))     # 1,000,000
print("{:0>8}".format(42))        # 00000042

15. f-string(Python 3.6+,最推荐)

name = "小明"
age = 20
print(f"我叫{name},今年{age}岁")

# 表达式计算
a, b = 3, 5
print(f"{a} + {b} = {a + b}")     # 3 + 5 = 8

# 格式化
pi = 3.1415926
print(f"圆周率:{pi:.2f}")         # 圆周率:3.14
print(f"二进制:{10:b}")           # 二进制:1010
print(f"百分比:{0.85:.1%}")       # 百分比:85.0%

七、编码与解码

16. encode() / decode()

s = "你好,世界"

# 编码为字节
b = s.encode('utf-8')
print(b)   # b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'

# 解码回字符串
print(b.decode('utf-8'))   # 你好,世界

八、实用综合案例

案例1:清理用户输入

defclean_input(text):
return text.strip().lower().replace('  ', ' ')

print(clean_input("  Hello  WORLD  "))
# hello world

案例2:提取文件名和扩展名

filename = "document.report.2024.pdf"
name, ext = filename.rsplit('.', 1)
print(f"文件名:{name}")    # document.report.2024
print(f"扩展名:{ext}")     # pdf

案例3:生成序号

for i in range(1, 6):
    print(f"编号:{str(i).zfill(3)}")
# 编号:001
# 编号:002
# 编号:003
# 编号:004
# 编号:005

案例4:统计单词频率

text = "hello world hello python hello code"
words = text.split()
word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1
print(word_count)
# {'hello': 3, 'world': 1, 'python': 1, 'code': 1}

九、方法速查表

方法
功能
len(s)
获取长度
s[i]
索引取值
s[a:b]
切片
s.find()
 / s.index()
查找位置
s.count()
统计次数
s.startswith()
 / s.endswith()
开头/结尾判断
s.replace()
替换
s.upper()
 / s.lower()
大小写转换
s.strip()
去除空白
s.split()
分割
s.join()
连接
s.center()
 / s.ljust() / s.rjust()
对齐
s.zfill()
前导补零
s.format()
 / f"..."
格式化
s.encode()
 / s.decode()
编码解码

💡 小贴士:字符串在 Python 中是不可变的,所有修改方法都会返回新字符串,原字符串不会被改变。

整理不易,觉得有用的话欢迎点赞收藏转发!

最新文章

随机文章