字符串处理:Python内置字符串函数详解
发布时间:2023-06-30 23:43:49
Python内置了很多字符串函数,可以对字符串进行各种操作和处理。下面是对常用的几个字符串函数进行详细介绍:
1. len() 函数:返回字符串的长度。
example_str = "Hello, world!" print(len(example_str)) # 输出:13
2. strip() 函数:去除字符串首尾的指定字符,默认去除空格。
example_str = " Hello, world! " print(example_str.strip()) # 输出:"Hello, world!"
3. split() 函数:将字符串按照指定的分隔符分割成列表。
example_str = "Hello, world!"
print(example_str.split(",")) # 输出:['Hello', ' world!']
4. join() 函数:将列表中的字符串按照指定的连接符连接成一个字符串。
example_list = ['Hello', 'world!']
print(",".join(example_list)) # 输出:"Hello,world!"
5. replace() 函数:将字符串中的指定子串替换成另一个子串。
example_str = "Hello, world!"
print(example_str.replace("Hello", "Hi")) # 输出:"Hi, world!"
6. lower() 函数:将字符串转换成小写字母。
example_str = "Hello, world!" print(example_str.lower()) # 输出:"hello, world!"
7. upper() 函数:将字符串转换成大写字母。
example_str = "Hello, world!" print(example_str.upper()) # 输出:"HELLO, WORLD!"
8. find() 函数:查找字符串中指定子串的索引位置,若不存在返回-1。
example_str = "Hello, world!"
print(example_str.find("world")) # 输出:7
9. count() 函数:统计字符串中指定子串的出现次数。
example_str = "Hello, world!"
print(example_str.count("o")) # 输出:2
10. startswith() 函数:判断字符串是否以指定子串开头。
example_str = "Hello, world!"
print(example_str.startswith("Hello")) # 输出:True
通过学习和使用这些字符串函数,你可以更方便地对字符串进行各种操作和处理,提高你编写Python程序的效率。
