python字符串的方法
方法 | 用法 |
---|
capitalize | 字符串首字母大写 | title | 每个单词的首字母大写 (非字母隔开的单词) | upper | 将所有字母变成大写 | swapcase | 大小写互换 | count | 统计字符串中某个元素的数量 | find | 查找某个字符串第一次出现的索引位置 | index | 与 find 功能相同 find找不到返回-1,index找不到数据直接报错 | startswith | 判断是否以某个字符或字符串为开头 | endswith | 判断是否以某个字符或字符串结尾 | split | 按某字符将字符串分割成列表(默认从左到右按空格分割) | join | 按某字符将列表拼接成字符串(容器类型都可) | replace | 替换字符串(第三个参数选择替换的次数) |
s = "hello world!"
res = s.capitalize()
print(res)
s = "xiao ming"
res = s.title()
print(res)
ss = "xiao20ming"
res = ss.title()
print(res)
s = "da xie"
res = s.upper()
print(res)
s = "XIAO Xie"
res= s.lower()
print(res)
s = "HU huan"
res = s.swapcase()
print(res)
s = "fdjzdcdsssjcdhkxnashzd"
res = s.count("s")
print(res)
res = s.count("s",15)
print(res)
res = s.count("s",0,9)
print(res)
s = "01234560123456"
res = s.find("1")
print(res)
res = s.find("1",3)
print(res)
res = s.find("1",3,6)
print(res)
s = "01234560123456"
res = s.index("2")
print(res)
s = "hello woeld!"
res = s.startswith("he")
print(res)
res = s.startswith("he",2)
print(res)
res = s.startswith("he",0,1)
print(res)
s = "hello woeld"
res = s.endswith("ld")
print(res)
res = s.endswith("ld",-1)
print(res)
res = s.endswith("ld",-5,-1)
print(res)
s = "a b c d e"
res = s.split()
print(res)
s = "a+b+c+d+e"
res = s.split("+")
print(res)
res = s.split("+",2)
print(res)
ls = ['0','1','2','3','4','5','6']
res = ''.join(ls)
print(res)
res = '+'.join(ls)
print(res)
s = "a1 b1 c1 a2 b2 c2 a1 a1"
res = s.replace("a1","aa")
print(res)
res = s.replace("a1","aa",1)
print(res)
方法 | 用法 |
---|
isupper | 判断字符串是否都是大写字母 | islower | 判断字符串是否都是小写字母 | istitle | 判断字符串是否每个单词都首字母大写 | isalnum | 判断字符串是否是由数字、字母、文字组成 | isalpha | 判断字符串是否由字母和文字组成 | isdigit | 检测字符串数是数字组成 接受二进制字节流 | isdecimal | 检测字符串是否以数字组成 必须是纯数字 | isnumeric | 检测字符串是否以数字组成 接受中文"四" | isspace | 判断字符串是否由空白符组成 |
s = "AABB"
ss = "Ab"
print(s.isupper())
print(ss.isupper())
s = "ab"
ss = "Ab"
print(s.islower())
print(ss.islower())
方法 | 用法 |
---|
splitlines | 按换行来进行切分(\n) | zfill | 填充字符串(默认填充0,原字符串右对齐) | ljust | 填充字符串,原字符居左 (默认填充空格) | rjust | 填充字符串,原字符居右 (默认填充空格) | center | 填充字符串,原字符居中 (默认填充空格) | strip | 默认去掉首尾两边的空白符 | rstrip | 去掉右边某个字符 | lstrip | 去掉左边某个字符 |
s = '111\n222'
print(s.splitlines())
s = "哈哈"
print(s.zfill(10))
s = "哈哈"
print(s.ljust(20,"*"))
s = "哈哈"
print(s.rjust(20,"+"))
s = "哈哈"
print(s.center(20,"-"))
|