搜索文档
首字母大写
方法:capitalize()
方法描述
- 将字符串的首字母转大写。
- 字符串内除首字母外其他位置的字符都转为小写。
语法:
str.capitalize()
参数:无
代码:
pythona = 'abcdefABCDEF' print(a.capitalize())运行结果:
注意事项
- capitalize() 方法只对第一个字母有效。
- capitalize() 方法只对字母有效,字符串首个字符若是数字则无效。
- capitalize() 方法对首字母已是大写的字符串无效。
转小写
方法:casefold() / lower()
方法描述
- casefold() 和 lower() 函数都可以把字符串中的大写字母转为小写。
- lower() 在 Python 最初的版本中就已经存在了,而 casefold() 是在 Python3.3 以后才出现的。
- 两者的区别在于,lower() 只能将字符串中的大写英文转为小写。而 casefold() 支持更多语言的大写转小写,例如:俄语。
语法:
str.casefold() / 字符串.lower()
参数:无
代码:
pythona = "ABCdefGG" print(a.casefold()) print(a.lower())运行结果:
转大写
方法:upper()
方法描述
- 把字符串中所有字符转为大写。
- 只对英文字符有效。
语法:
str.upper()
参数:无
代码:
pythona = 'AbcDef' print(a.upper())运行结果:
大小写互转
方法:swapcase()
方法描述
- 将字符串内大写字符转为小写字符,同时将小写字符转为大写字符。
- 只对英文字符有效。
语法
str.swapcase()
参数:无
代码:
pythona = 'AbcDef' print(a.swapcase())运行结果:
自定义字符串长度
方法:zfill()
方法描述
- 用于修改字符串的长度,也可以说是给字符串指定长度。
- 当字符串实际长度小于 zfill() 方法设置的长度时,用 0 补齐。
语法
str.zfill(width)
参数:width - 指定长度。
代码:
pythona = 'abc' print(a.zfill(10))运行结果:
统计字符出现的次数
方法:count()
方法描述
- 用于返回某个字符在一个字符串中出现的次数。
- 若查询的字符不在字符串中,则返回 0。
语法
str.count(item)
参数:item - 要查找的字符
代码:
pythona = 'This file is Python code' print(a.count('i')) print(a.count('is')) print(a.count('g'))运行结果:
判断首尾元素
方法:startswith() / endswith()
方法描述
- startswith() 方法用于判断首字符是否为某个值。
- endswith() 方法用于判断尾字符是否为某个值。
语法
str.startswith(item) / str.endswith(item)
参数:item - 指定字符
代码:
pythona = 'This file is Python code' print(a.startswith('T')) print(a.startswith('a')) print(a.endswith('e')) print(a.endswith('b'))运行结果:
查找字符
方法:find() / index()
方法描述
- 返回某个元素在字符串中第一次出现的位置。
- 字符串里的位置是从左向右的,以 0 开始。
- find() 方法在找不到元素时,返回 -1。
- index() 方法找不到元素时,直接报错。
- 推荐使用 find()
语法
str.find(item) / str.index(item)
参数:item - 要查找的字符
代码:
pythona = 'This file is Python code' print(a.find('file')) print(a.find('ok')) print(a.index('file')) print(a.index('ok'))运行结果
去掉字符串两端的字符
方法:strip()
方法描述
- 用于去掉字符串两端的字符。
- 默认情况下,不传参表示去掉空格。
语法
str.strip(item)
参数:itme - 要去掉的字符
代码:
pythona = 'This file is Python code' b = ' 0 abc 0 ' print(a.strip('T')) print(a.strip('de')) print(b.strip())运行结果
扩展
- lstrip() 方法:去掉字符串开头的指定元素或空格。
- rstrip() 方法:去掉字符串结尾的指定元素或空格
替换元素
方法:replace()
方法描述
- 将字符串中旧元素替换成新元素。
- 可以指定替换的数量
语法
str.replace(old,new,max)
参数:
- old:被替代的元素
- new:取代 old 的新元素
- max:可选,代表替换几个,默认替换全部。
代码:
pythona = 'This file is Python code' print(a.replace('i','-i-')) print(a.replace('i','-i-',1))运行结果:
判断方法
isspace()
isspace() 用于判断一个字符串是否由空格组成。
若字符串内全是空格则方法返回 True,否则返回 False。
代码:
pythonstr0 = ' ' str1 = ' abc ' print(str0.isspace()) print(str1.isspace())运行结果:
istitle()
istitle() 用于判断一个字符串是否为标题字符串。
标题字符串的定义:字符串内有多个单词,单词之间用空格分开,并且每个单词的首字母大写,这样的字符串被称为标题字符串。
字符串是标题字符串时返回 True,否则返回 False。
代码:
pythonstr0 = 'Hello Tom' str1 = 'Hello jom' print(str0.istitle()) print(str1.istitle())运行结果:
isupper() 和 islower()
isupper():判断字符串内所有字符是否都是大写。
islower():判断字符串内所有字符是否都是小写。
代码:
pythonstr0 = 'HELLO WORLD' str1 = 'hello world' print(str0.isupper()) print(str0.islower()) print(str1.isupper()) print(str1.islower())运行结果:
