Python字符串操作避坑指南:3个技巧让你效率翻倍

21 阅读2分钟

20251226203800_65_41.jpg

这是一份有基础、有深度的 Python 必备秘籍。

字符串常用操作

################## 初始化 的三种方式
>>> s1 = 'hello'
>>> s2 = "hello"
>>> s3 = """hello"""
>>> s1 == s2 == s3
True

>>> s4 = "I'm a student."
>>> s4
"I'm a student."

################## 切片
>>> name = 'jason'
>>> name[0]
'j'
>>> name[1:3]
'as'

################## 遍历
>>> for char in name:
>>>     print(char)   
j
a
s
o
n

################## 字符串是不可变的
s = 'hello'
s[0] = 'H'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

################## 如果,要实现字符串变量修改,需要新建一个字符串
s = 'H' + s[1:]
s = s.replace('h', 'H')

################## 字符串拼接
str1 += str2  # 表示 str1 = str1 + str2,打破了字符串不可变的特性。

# 再看下 for 循环里面使用 +=
s = ''
for n in range(0, 100000):
    s += str(n)

# 使用 join
l = []
for n in range(0, 100000):
    l.append(str(n))
l = ' '.join(l) 


# 在 Python2.5 开始,处理字符串拼接时(如,str1 += str2)。
# Python 会先检测 str1 还有没有其他的引用。
# 如果没有,就会尝试原地扩充字符串 buffer 的大小。而不是重新分配一块内存,来创建新字符串,并拷贝。
# 这样,上面代码的时间复杂度是 `O(n)`

##################  分割
path = 'hive://ads/training_table'
namespace = path.split('//')[1].split('/')[0] # 返回'ads'
table = path.split('//')[1].split('/')[1] # 返回 'training_table'

##################  其他:strip()、lstrip()、rstrip()

字符串格式化

先看结论

# Python 3.6 之前,推荐 format 方式
sentence = "Hi {}"
print(sentence.format(first_name))  # 输出:Hi Eric

# Python 3.6+,推荐 f-string 方式
print(f"Hi {first_name}")    # 输出:Hi Eric

演示代码

first_name = "Eric"
print(first_name)   # 输出: Eric

# 1. 这里使用 "+" 拼接字符串和字符串变量
print("Hi " + first_name)   # 输出:Hi Eric

# 2. 使用 f 方式,得到相同的输出,
print(f"Hi {first_name}")    # 输出:Hi Eric

# 使用 f 方式,接收多个参数
print(f"Hi {first_name} {last_name}...")  # 输出:Hi Eric Roby...

# 3. 使用 format 方式,得到相同的输出
sentence = "Hi {}"
print(sentence.format(first_name))  # 输出:Hi Eric

# 使用 format 方式,接收多个参数
sentence2 = "Hi {} {}"
last_name = "Roby"
print(sentence2.format(first_name, last_name))  # 输出:Hi Eric Roby

-------- 写在最后 --------

关注我,每天1分钟,轻松懂 Python

我的同名公众号正在连载《FastAPI 开发实战》、《Python 核心技术》、《Python 自动化办公》《职场》。


点赞 :如果觉得有收获,点赞支持一下吧!

分享 :分享给身边同样对Python感兴趣的朋友!

关注我 :不要错过每一篇 Python 实战内容!


#Python #FastAPI #API #Web开发 #程序员 #编程教程 #效率提升