Python中的字符串函数教程
发布时间:2023-06-09 23:57:50
Python中的字符串是非常强大和灵活的。字符串是 Python 中最常用的数据类型之一。 Python中有大量的字符串函数和方法,可以帮助我们处理字符串。
下面列出了一些最常用的字符串函数,让我们一起来学习。
1. len(s): 返回字符串s的长度。
示例:
s = "hello, world!" print(len(s)) # 输出 13
2. capitalize(): 将字符串的第一个字符转换为大写。
示例:
s = "hello, world!" print(s.capitalize()) # 输出 Hello, world!
3. upper(): 将字符串中所有字符转换为大写。
示例:
s = "hello, world!" print(s.upper()) # 输出 HELLO, WORLD!
4. lower(): 将字符串中所有字符转换为小写。
示例:
s = "HELLO, WORLD!" print(s.lower()) # 输出 hello, world!
5. swapcase(): 将字符串中所有大写字母转换为小写字母,将所有小写字母转换为大写字母。
示例:
s = "Hello, World!" print(s.swapcase()) # 输出 hELLO, wORLD!
6. title(): 将字符串中所有单词的首字母大写。
示例:
s = "hello, world!" print(s.title()) # 输出 Hello, World!
7. strip(): 去除字符串开头和结尾的空白符,例如空格和换行符。
示例:
s = " hello, world! " print(s.strip()) # 输出 hello, world!
8. replace(): 替换字符串中指定的子字符串为另一个字符串。
示例:
s = "hello, world!"
print(s.replace("world", "python")) # 输出 hello, python!
9. count(substring): 返回子字符串在字符串中出现的次数。
示例:
s = "hello, world!"
print(s.count("l")) # 输出 3
10. find(substring): 返回子字符串第一次出现在字符串中的位置,如果没有找到,则返回-1。
示例:
s = "hello, world!"
print(s.find("world")) # 输出 7
以上是Python中常用的字符串函数,如果有需要可以查看官方文档,或者自行查询一下相关的资料。字符串函数非常实用,可以帮助我们高效地处理字符串。
