Python学习---高效字符串处理技巧

一、字符串拼接

1.1 使用 + 运算符

python 复制代码
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)  # 输出:Hello World

1.2 使用 join() 方法

join() 方法可以有效地连接多个字符串,尤其是在连接列表或其他可迭代对象时,非常高效。

python 复制代码
words = ["Hello", "World"]
result = " ".join(words)
print(result)  # 输出:Hello World

1.3 使用 f-strings (格式化字符串)

python 复制代码
name = "Alice"
age = 30
result = f"My name is {name} and I am {age} years old."
print(result)  # 输出:My name is Alice and I am 30 years old.

二、字符串分割

2.1 使用 split() 方法

split() 方法根据指定的分隔符将字符串分割为列表。

python 复制代码
sentence = "Python is awesome"
words = sentence.split()
print(words)  # 输出:['Python', 'is', 'awesome']

2.2 使用正则表达式进行分割

可以使用 re 模块的 split() 方法,支持更复杂的分割逻辑。

python 复制代码
import re

sentence = "Python,is,awesome"
words = re.split(',| ', sentence)
print(words)  # 输出:['Python', 'is', 'awesome']

三、去除空白字符

strip() 方法可以去除字符串头尾的空白字符;

lstrip() 方法去除左侧的空白字符;

rstrip() 方法去除右侧的空白字符。

python 复制代码
text = "  Hello World  "
clean_text = text.strip()
print(f"'{clean_text}'")  # 输出:'Hello World'

left_clean_text = text.lstrip()
right_clean_text = text.rstrip()
print(f"'{left_clean_text}', '{right_clean_text}'") 
# 输出:'Hello World  ', '  Hello World'

四、字符串查找、替换

4.1 查找

使用 in 关键字、find()、rfind()方法

in关键字:查看子字符串是否存在于字符串中;

find() 方法返回子字符串的第一个出现位置,找不到则返回 -1;

rfind() 则是从右侧开始查找。

python 复制代码
sentence = "Python is awesome"
result = "Python" in sentence
print(result)  # 输出:True

sentence = "Python is awesome. Python is dynamic."
first_occurrence = sentence.find("Python")
last_occurrence = sentence.rfind("Python")
print(first_occurrence, last_occurrence)  # 输出:0 19

4.2 替换

replace() 方法:将字符串中的某部分内容替换为新的内容,也可以删除特定部分;

正则表达式进行替换:复杂替换,可以使用 re 模块的 sub() 方法

python 复制代码
# replace
text = "Hello World"
new_text = text.replace("World", "Python")
print(new_text)  # 输出:Hello Python

# 正则表达式
import re
text = "Hello 123 World 456"
new_text = re.sub(r'\d+', '', text)
print(new_text)  # 输出:Hello  World 
相关推荐
Wy. Lsy5 分钟前
Kotlin基础学习记录
开发语言·学习·kotlin
The_Killer.9 分钟前
格密码--数学基础--06对偶空间与对偶格
学习·线性代数·密码学
彤银浦2 小时前
Web学习笔记3
前端·笔记·学习·html5
cooldream20092 小时前
Python 包管理新时代:深入了解 `uv` 的使用与实践
python·uv·包管理器
之歆2 小时前
Python-魔术方法-创建、初始化与销毁-hash-bool-可视化-运算符重载-容器和大小-可调用对象-上下文管理-反射-描述器-二分-学习笔记
笔记·python·学习
优乐美香芋味好喝2 小时前
2025年7月11日学习笔记&一周归纳——模式识别与机器学习
笔记·学习·机器学习
胖达不服输2 小时前
「日拱一码」025 机器学习——评价指标
人工智能·python·机器学习·评价指标
brave_zhao3 小时前
JavaBeanUtils javaBean转map, 实体类转map,实体集合转List<Map>
linux·windows·python
声网4 小时前
对话 AI 陪伴新宠 Tolan 创始人:拒绝「恋爱脑」,「非人」陪伴更受欢迎?丨 Voice Agent 学习笔记
人工智能·笔记·学习
丁满与彭彭4 小时前
嵌入式学习笔记--MCU阶段--day03中断
笔记·单片机·学习