Python中的字符串函数:10种常用函数介绍
Python中的字符串函数是非常强大的,以至于有时候我们可能会忽略其中一些非常有用的方法。在这篇文章中,我们将介绍10种常用的字符串函数功能,并详细说明其用法。
1、lower() / upper()
lower() 将字符串中的所有字符转换为小写,而 upper() 则将其转换为大写。这两个函数都返回转换后的新字符串。
例如:
string = "Hello World" print(string.lower()) # 输出:"hello world" print(string.upper()) # 输出:"HELLO WORLD"
2、strip()
strip() 函数用于删除字符串前面和后面的空格或指定字符。默认情况下,该函数会删除字符串前后的空格,但是我们也可以通过指定参数来删除特定字符。
例如:
string = " hello "
print(string.strip()) # 输出:"hello"
string = "hello, world!"
print(string.strip("!")) # 输出:"hello, world"
3、split()
split() 函数将一个字符串分割成一个字符串列表,其中每个元素都是从原始字符串中分隔符的分割。
例如:
string = "apple, banana, cherry"
print(string.split(",")) # 输出:['apple', ' banana', ' cherry']
4、join()
join() 函数用于连接字符串列表。在应用时,我们需要指定分隔符,并将其传递给 join() 函数。
例如:
list_of_strings = ['apple', 'banana', 'cherry']
print(", ".join(list_of_strings)) # 输出:"apple, banana, cherry"
5、replace()
replace() 函数用于将字符串中的一个子字符串替换为另一个子字符串。我们需要传递两个参数:要被替换的子字符串和替换子字符串。
例如:
string = "I like to eat apples"
print(string.replace("apples", "bananas")) # 输出:"I like to eat bananas"
6、startswith() / endswith()
startswith() 函数用于检查字符串是否以指定的子字符串开头,而 endswith() 则用于检查字符串是否以指定的子字符串结尾。两个函数都返回布尔值:True 或者 False
例如:
string = "Hello World"
print(string.startswith("Hello")) # 输出:True
print(string.endswith("World")) # 输出:True
7、find() / index()
find() 函数用于返回字符串中子字符串的 个匹配项的索引,如果子字符串不存在,则返回 -1。而 index() 同样用于返回子字符串的索引,但如果子字符串不存在,则会引发 ValueError 异常。
例如:
string = "Hello World"
print(string.find("World")) # 输出:6
print(string.find("Python")) # 输出:-1
string = "Hello World"
print(string.index("World")) # 输出:6
try:
print(string.index("Python")) # 会引发 ValueError 异常
except ValueError:
print("Substring not found")
8、count()
count() 函数用于返回字符串中指定子字符串的出现次数。
例如:
string = "Hello World"
print(string.count("l")) # 输出:3
9、capitalize() / title()
capitalize() 函数用于将字符串的 个字符转换为大写,而 title() 函数则用于将字符串中每个单词的首字母都转换为大写。
例如:
string = "hello world" print(string.capitalize()) # 输出:"Hello world" print(string.title()) # 输出:"Hello World"
10、isnumeric() / isalpha() / isalnum()
isnumeric() 函数用于检查字符串中是否只包含数字字符。如果是,则返回 True,否则返回 False。
isalpha() 函数用于检查字符串中是否只包含字母字符。如果是,则返回 True,否则返回 False。
isalnum() 函数用于检查字符串中是否仅包含字母和数字字符。如果是,则返回 True,否则返回 False。
例如:
string = "1234" print(string.isnumeric()) # 输出:True print(string.isalpha()) # 输出:False print(string.isalnum()) # 输出:True
这些是 Python 中10种常用的字符串函数,希望这篇文章能对您的日常开发工作有所帮助!
