python字符串相关函数

2018-11-08  本文已影响0人  憧憬001

Python 的字符串常用内建函数如下:

1.统计

str1 = "123456789066666"
print(str1.count("6"))
print(len(str1))


执行结果:6、15

2.对齐

str1 = '居中'
new_str = str1.center(8, '*')
print(new_str)

str2 = "左对齐"
new_str = str2.ljust(7, '*')
print(new_str)
str3 = "右对齐"
new_str = str3.rjust(7, '*')
print(new_str)

效果如下

***居中***
左对齐****
****右对齐

3.最值

print(max('ahajsxnzh4784mkou'))
print(min('ftyrejibhxnzh23456njiu'))

4.查找与替换

查找
str1 = "123456"
print(str1.startswith("12"))
print(str1.endswith("6"))

执行结果:都是True

str1 = "123456"
print(str1.find("3"))
print(str1.rfind("6"))
print(str1.find("7"))
print(str1.index("3"))
print(str1.rindex("6"))
2
5
-1
2
5
替换
str1 = "123456"
str2 = "abc"
print(str1.replace("123", str2))

执行结果:abc456

str1 = 'hello'
new_str = str1.capitalize()
print(new_str)

执行结果:Hello

str1 = "abc***DEF***123456"
print(str1.upper())
print(str1.lower())
print(str1.swapcase())
ABC***DEF***123456
abc***def***123456
ABC***def***123456

5.判断

str3 = "123456abc"
print(str3.isalnum())
print(str3.isalpha())
print(str3.isdigit())
print(str3.isdecimal())

执行结果:True、False、False、False

str3 = "123456abc"
print(str3.islower())
print(str3.isupper())

执行结果:True、False

str4 = "123一二三壹幺萬"
str5 = " "
str6 = "Asjdkjdk123"
print(str4.isnumeric())
print(str5.isspace())
print(str6.istitle())

执行结果:True、True、True

6.截取、合并和删除

str2 = "  000 000**00"
print(str2.lstrip())
str3 = "**0000   "
print(str3.lstrip("**"))
str4 = "123abc000"
print(str4.split("23"))
print(str3.rstrip())

str5 = '**'
str6 = 'abc'
print(str5.join(str6))

000 000**00
0000
['1', 'abc000']
**0000
a**b**c

7.其他

上一篇下一篇

猜你喜欢

热点阅读