Python中的字符串函数:从基本函数到高级操作
Python是一种高级编程语言,其中字符串是最常用的数据类型之一。Python字符串是以Unicode字符序列表示的不可变序列。“字符串”这个词必须是放在引号之间的文本。Python字符串是一种有序的字符集合,可以通过索引访问它们。本文将介绍一些Python中有用的字符串函数,包括基本函数和高级操作。
基本字符串函数
1. len(): 返回字符串的长度
str = "Python" print(len(str)) # 6
2. lower(): 把字符串中的所有大写字母转换成小写字母
str = "HELLO WORLD" print(str.lower()) # hello world
3. upper(): 把字符串中的所有小写字母转换成大写字母
str = "hello world" print(str.upper()) # HELLO WORLD
4. capitalize(): 把字符串第一个字符转换成大写字母,其他字符转换成小写字母
str = "hello world" print(str.capitalize()) # Hello world
5. replace(): 将字符串中的指定子字符串替换成另一个子字符串
str = "hello world"
print(str.replace("world", "python")) # hello python
6. split(): 根据指定的分隔符,分割字符串为一个子字符串列表
str = "hello,world"
print(str.split(",")) # ['hello', 'world']
7. strip(): 去除字符串两端的空格或指定的字符,默认是空格
str = " hello world " print(str.strip()) #hello world
高级字符串操作
1. 字符串拼接
Python的字符串拼接可以使用"+"运算符,也可以使用简化的"+="运算符。
str1 = "hello" str2 = "world" str3 = str1 + str2 print(str3) # helloworld str1 += str2 print(str1) # helloworld
2. 字符串格式化
Python的字符串格式化可以使用format()和f-string两种方法。
使用format()方法:
name = "Tom"
age = 22
print("My name is {}, and I am {} years old.".format(name, age))
# My name is Tom, and I am 22 years old.
使用f-string方法:
name = "Tom"
age = 22
print(f"My name is {name}, and I am {age} years old.")
# My name is Tom, and I am 22 years old.
3. 正则表达式
正则表达式是一种用于匹配文本的强大工具。Python提供了re模块来操作正则表达式。下面是一个匹配数字的例子:
import re
string = "The phone number is 123-456-7890. Call me back."
pattern = r"\d{3}-\d{3}-\d{4}"
match = re.search(pattern, string)
if match:
print("Phone number found: " + match.group())
else:
print("Phone number not found.")
# Phone number found: 123-456-7890
4. 字符串编码解码
Python中的字符串默认是Unicode编码。有时候需要将Unicode编码转换成其他编码格式,例如ASCII、UTF-8等。可以使用encode()方法将Unicode编码转换成其他编码格式,使用decode()方法将其他编码格式转换成Unicode编码。
string = "编码转换"
encoded = string.encode("UTF-8")
print(encoded) # b'\xe7\xbc\x96\xe7\xa0\x81\xe8\xbd\xac\xe6\x8d\xa2'
decoded = encoded.decode("UTF-8")
print(decoded) # 编码转换
总结
本文介绍了Python中常用的字符串函数,包括基本函数和高级操作。使用这些函数可以方便地操作字符串,提高编程效率。
