欢迎访问宙启技术站
智能推送

10个Python中常用的字符串操作函数

发布时间:2023-06-05 09:45:24

字符串是一种在 Python 中十分常见的数据类型,因此 Python 提供了很多用于处理字符串的操作函数。在这篇文章中,我将介绍 Python 中最常用的 10 个字符串操作函数,以及它们的使用方法。

1. len()

len() 函数可以返回字符串的长度。它的使用方法非常简单,就是直接传入一个字符串作为参数即可。例如:

str = "Hello, World!"
print(len(str))

这个程序会输出 13,因为字符串 "Hello, World!" 中包含了 13 个字符。

2. capitalize()

capitalize() 函数可以将字符串中的每个单词的首字母大写。例如:

str = "this is a test string."
print(str.capitalize())

这个程序会输出 "This is a test string."。

3. upper()

upper() 函数可以将字符串中的所有字母大写。例如:

str = "this is a test string."
print(str.upper())

这个程序会输出 "THIS IS A TEST STRING."。

4. lower()

lower() 函数可以将字符串中的所有字母小写。例如:

str = "THIS IS A TEST STRING."
print(str.lower())

这个程序会输出 "this is a test string."。

5. replace()

replace() 函数可以在一个字符串中替换指定的部分。它可以接受两个参数, 个参数是要替换的字符串,第二个参数是用于替换的字符串。例如:

str = "this is a test string."
print(str.replace("test", "example"))

这个程序会输出 "this is a example string."。

6. split()

split() 函数可以将一个字符串分割成多个子字符串,它的参数表示分隔符。例如:

str = "this is a test string."
print(str.split(" "))

这个程序会输出 ["this", "is", "a", "test", "string."],因为我们使用空格作为分隔符。

7. join()

join() 函数可以将多个字符串合并成一个,它的参数是一个字符串列表。例如:

lst = ["this", "is", "a", "test", "string."]
str = " ".join(lst)
print(str)

这个程序会输出 "this is a test string.",因为我们使用空格作为连接符。

8. strip()

strip() 函数可以移除字符串的两端的空白字符(包括空格、制表符、换行符等)。例如:

str = "  this is a test string.  "
print(str.strip())

这个程序会输出 "this is a test string.",因为我们移除了两端的空格字符。

9. find()

find() 函数可以查找一个字符串在另一个字符串中的位置,它的参数是要查找的字符串。例如:

str = "this is a test string."
print(str.find("test"))

这个程序会输出 10,因为字符串 "test" 在字符串 "this is a test string." 中的位置是从第 11 个字符开始的。

10. count()

count() 函数可以统计一个字符串中指定的字符出现的次数,它的参数是要统计的字符。例如:

str = "this is a test string."
print(str.count("i"))

这个程序会输出 3,因为字符 "i" 在字符串 "this is a test string." 中出现了 3 次。

以上就是 Python 中最常用的 10 个字符串操作函数,它们都非常实用,如果你经常使用字符串,那么它们对你一定会非常有帮助。