# 字符串函数
字符串是编程中经常使用的一种数据类型,它可以用来表示文本、数据等,在Python中,有许多内置的字符串函数可以帮助我们操作和处理字符串,下面是一些常用的字符串函数及其用法:
1. `len(string)`:返回字符串的长度。
string = "hello world" print(len(string)) # 输出:11
2. `str.upper(string)`:将字符串中的所有字母转换为大写字母。
string = "hello world" print(string.upper()) # 输出:HELLO WORLD
3. `str.lower(string)`:将字符串中的所有字母转换为小写字母。
string = "HELLO WORLD" print(string.lower()) # 输出:hello world
4. `str.strip(string)`:删除字符串前后的空格(或指定字符)。
string = " hello world " print(string.strip()) # 输出:hello world
5. `str.startswith(string, prefix)`:检查字符串是否以指定的前缀开头。
string = "hello world" print(string.startswith("hel")) # 输出:True
6. `str.endswith(string, suffix)`:检查字符串是否以指定的后缀结尾。
string = "hello world" print(string.endswith("rld")) # 输出:True
7. `str.replace(string, old, new)`:将字符串中的指定子串替换为新的子串。
string = "hello world" print(string.replace("world", "Python")) # 输出:hello Python
8. `str.split(string, delimiter)`:根据分隔符将字符串分割成多个子串。
string = "hello world" print(string.split(" ")) # 输出:['hello', 'world']
9. `str.join(iterable)`:将可迭代对象中的元素连接成一个字符串。
list_ = ["hello", "world"] print(" ".join(list_)) # 输出:hello world