
- capitalize():将字符串的第一个字符转换为大写字母。
pythonstring = "hello world"
print(string.capitalize()) # 输出: "Hello world"
- lower():将字符串中的所有大写字母转换为小写字母。
pythonstring = "HELLO WORLD"
print(string.lower()) # 输出: "hello world"
- upper():将字符串中的所有小写字母转换为大写字母。
pythonstring = "hello world"
print(string.upper()) # 输出: "HELLO WORLD"
- strip():删除字符串开头和结尾的空白字符(包括空格、制表符和换行符)。
pythonstring = " hello world "
print(string.strip()) # 输出: "hello world"
- replace():将字符串中的某个子串替换为另一个子串。
pythonstring = "hello world"
print(string.replace("world", "python")) # 输出: "hello python"
- split():将字符串按照指定的分隔符拆分成一个列表。
pythonstring = "hello,world,python"
print(string.split(",")) # 输出: ['hello', 'world', 'python']
- join():将一个列表中的元素以指定的分隔符连接成一个字符串。
pythonlist = ['hello', 'world', 'python']
print(",".join(list)) # 输出: "hello,world,python"
- find():查找子串在字符串中第一次出现的位置,如果找不到则返回-1。
pythonstring = "hello world"
print(string.find("world")) # 输出: 6
print(string.find("python")) # 输出: -1
- count():统计子串在字符串中出现的次数。
pythonstring = "hello world, hello python"
print(string.count("hello")) # 输出: 2