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

Python字符串操作常用函数

发布时间:2023-06-11 19:52:10

Python 是一种广泛使用的开源高级编程语言,它可运行于各种操作系统上,也可用于开发各种类型的应用程序。Python 具有许多优点,包括易于学习、可维护、具有广泛的标准库、可运行于不同平台等。在 Python 中,字符串是最常见的数据类型之一,字符串表示文本,可以使用许多操作函数对字符串进行处理。这篇文章将介绍 Python 中常用的字符串操作函数。

1. len()函数

len() 函数用于返回字符传的长度。例如:

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

输出结果为 13。

2. lower()函数

lower() 函数用于将字符串中所有的大写字母转换成小写字母。例如:

str = "Hello, World!"
print(str.lower())

输出结果为 hello, world!。

3. upper()函数

upper() 函数用于将字符串中所有的小写字母转换成大写字母。例如:

str = "Hello, World!"
print(str.upper())

输出结果为 HELLO, WORLD!。

4. capitalize()函数

capitalize() 函数用于将字符串第一个字符转换成大写字母,其它字符转换成小写字母。例如:

str = "hello, world!"
print(str.capitalize())

输出结果为 Hello, world!。

5. title()函数

title() 函数用于将字符串中每个单词首字母转换成大写字母,其余字符转换成小写字母。例如:

str = "hello, world!"
print(str.title())

输出结果为 Hello, World!。

6. replace()函数

replace() 函数用于将字符串中的指定子串替换成另一个子串。例如:

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

输出结果为 hello, python!。

7. split()函数

split() 函数用于将字符串按照给定的分隔符分割成多个子字符串。例如:

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

输出结果为 ['hello', ' world!']。

8. join()函数

join() 函数用于将多个字符串连接成一个字符串。例如:

str1 = "hello"
str2 = "world"
print(" ".join([str1, str2]))

输出结果为 hello world。

9. strip()函数

strip() 函数用于去除字符串首尾指定字符或空格。例如:

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

输出结果为 hello, world!。

10. startswith()函数

startswith() 函数用于判断字符串是否以指定的子串开头。例如:

str = "hello, world!"
print(str.startswith("hello"))

输出结果为 True。

以上是 Python 中常用的字符串操作函数。在实际开发中,这些函数可以帮助我们处理字符串,提升开发效率。要了解更多关于 Python 的字符串操作函数,可以查看 Python 官方文档。