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

Python中的字符串函数:了解字符串操作的常见函数

发布时间:2023-06-13 18:06:35

Python中的字符串是一种非常常用的数据类型。其强大的字符串操作函数可以处理各种字符串操作,这些操作包括字符串的拼接、截取、搜索等等。

本文将简单介绍Python中的一些常见字符串函数。

1. len() 函数

len() 函数返回一个字符串的长度。

例如:

str = "Hello World!"

print("字符串长度为:", len(str))

输出结果为:

字符串长度为: 12

2. upper() 函数

upper() 函数将字符串中的所有小写字母转换为大写字母。

例如:

str = "Hello World!"

print("大写字符串为:", str.upper())

输出结果为:

大写字符串为: HELLO WORLD!

3. lower() 函数

lower() 函数将字符串中的所有大写字母转换为小写字母。

例如:

str = "Hello World!"

print("小写字符串为:", str.lower())

输出结果为:

小写字符串为: 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. center() 函数

center() 函数将字符串居中,并使用指定的字符填充左右两侧的空格。

例如:

str = "Hello"

print("居中字符串为:", str.center(20, "*"))

输出结果为:

居中字符串为: *******Hello********

7. count() 函数

count() 函数返回子字符串在字符串中出现的次数。

例如:

str = "Hello World!"

sub_str = "o"

print("字符串中'o'出现的次数为:", str.count(sub_str))

输出结果为:

字符串中'o'出现的次数为: 2

8. find() 函数

find() 函数查找子字符串在字符串中 次出现的位置,并返回该位置的索引。

例如:

str = "Hello World!"

sub_str = "o"

print("子字符串位置为:", str.find(sub_str))

输出结果为:

子字符串位置为: 4

9. replace() 函数

replace() 函数用指定的字符串替换字符串中指定的子字符串。

例如:

str = "Hello World!"

old_str = "World"

new_str = "Python"

print("替换后的字符串为:", str.replace(old_str, new_str))

输出结果为:

替换后的字符串为: Hello Python!

10. split() 函数

split() 函数将字符串分割成一个列表,分隔符由参数指定。

例如:

str = "Hello World!"

print("分割后的结果为:", str.split(" "))

输出结果为:

分割后的结果为: ['Hello', 'World!']

以上是Python中的一些常见字符串操作函数,不过这些函数只是冰山一角,Python中还有很多其他的字符串操作函数。如果你使用字符串操作较多,那么你应该学会这些函数,这将大大提高你编写Python程序的效率。