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

Python中最常用的10个字符串函数,帮你轻松处理字符串

发布时间:2023-05-26 06:54:08

Python是一种非常强大且易于使用的编程语言,其内置了许多用于处理字符串的函数。在这篇文章中,我们将介绍 Python 中最常用的 10 个字符串函数,让你能够更轻松地处理字符串。

1. len() 函数

len() 函数是 Python 中用于获取字符串长度的函数。它的用法非常简单:只需要在函数名后面加上要统计长度的字符串即可。例如:

str = "hello"
print(len(str))

输出结果为:

5

2. str() 函数

str() 函数用于将其他类型的数据转换为字符串。它的用法是将要被转换的数据作为函数参数传入即可,例如:

num = 123
str_num = str(num)
print(str_num)

输出结果为:

123

3. upper() 和 lower() 函数

upper() 函数将字符串中所有的字母都变成大写字母,而 lower() 函数则将字符串中所有的字母都变成小写字母。它们的用法非常简单:

str = "hello"
str_upper = str.upper()
str_lower = str.lower()
print(str_upper)
print(str_lower)

输出结果为:

HELLO
hello

4. replace() 函数

replace() 函数用于替换字符串中指定的子字符串。它的用法是将要被替换的子字符串和要替换成的新字符串作为函数参数传入即可,例如:

str = "hello, world!"
new_str = str.replace("world", "python")
print(new_str)

输出结果为:

hello, python!

5. count() 函数

count() 函数用于统计字符串中指定子字符串出现的次数。它的用法是将要被统计的子字符串作为函数参数传入即可,例如:

str = "hello, world!"
count = str.count("l")
print(count)

输出结果为:

3

6. join() 函数

join() 函数用于将一个字符串列表用指定分隔符连起来,形成一个新的字符串。它的用法是将要被连接的字符串列表作为 join() 函数的参数传入,同时在参数列表中指定分隔符即可,例如:

str_list = ["hello", "world"]
str_join = ",".join(str_list)
print(str_join)

输出结果为:

hello,world

7. split() 函数

split() 函数用于将一个字符串根据指定分隔符拆分成一个字符串列表。它的用法是将要被拆分的字符串和分隔符作为参数传入即可,例如:

str = "hello,world"
str_list = str.split(",")
print(str_list)

输出结果为:

['hello', 'world']

8. strip() 函数

strip() 函数用于去除字符串首尾的空格或指定字符。它的用法是在函数名后面添加要去除的字符即可,默认情况下是去除空格,例如:

str = "  hello, world!  "
new_str = str.strip()
print(new_str)

输出结果为:

hello, world!

9. find() 和 index() 函数

find() 和 index() 函数都用于查找字符串中是否包含指定的子字符串,不同的是,如果字符串中不存在指定的子字符串,find() 函数返回 -1,而 index() 函数会抛出异常。它们的用法是将要被查找的子字符串作为参数传入即可,例如:

str = "hello, world!"
index = str.find("world")
print(index)

index = str.index("python")
print(index)

输出结果为:

7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

10. startswith() 和 endswith() 函数

startswith() 和 endswith() 函数用于判断字符串是否以指定的子字符串开头或结尾。它们的用法是将要被判断的子字符串作为参数传入即可,例如:

str = "hello, world!"
is_start = str.startswith("hello")
is_end = str.endswith("python")
print(is_start)
print(is_end)

输出结果为:

True
False

以上就是 Python 中最常用的 10 个字符串函数,它们无疑能够让你更轻松地处理字符串,让你在处理字符串时更加得心应手。