检测机制
startswith
"Brevity is the soul of wit".startswith("Bre")
>>True
#判断索引[1,3)中的元素,值是否为"re"
"Brevity is the soul of wit".startswith("re",1,3)
>>True
endswith
"Brevity is the soul of wit".endswith("re",1,3)
>>True
isupper 判断是否至少存在一个大写字母,且所有字母均大写
"BREVITY你好 \n123".isupper()
>>True
islower 判断是否至少存在一个小写字母,且所有字母均小写
"brevity你好 \n123".islower()
>>True
isdigit 判断是否全部为非负整数
"-1\n\r".isdigit()
>>False
"1".isdigit()
>>True
isalpha 判断是否全部为字母
"Aaasdwe".isalpha()
>>True
"a\rs".isalpha()
>>False
isalnum 判断是否全部为非负整数或字母(即 isdigit or isalpha)
"A 1".isalnum()
>>False
"A231SD".isalnum()
>>True
isspace 判断是否全为空格(包含制表符)
"\r\n\t ".isspace()
>>True
"".isspace()
>>False
istitle 判断是否为首字母大写(忽略非字母字符)
"Brevity is the soul of wit".istitle()
>>False
"Brevity Is The Soul Of Wit".istitle()
>>True
isdecimal 判断是否全为阿拉伯数字非负整数(只接受unicode形式输入)
"1".isdecimal()
>>AttributeError:"str" object has no attribute "isdecimal"
u"3".isdecimal()
>>True
u"IV".isdecimal()
>>False
isnumeric 判断是否全为非负整数(只接受unicode形式输入)
u"1".isnumeric()
>>True
u"一".isnumeric()
>>True
u"壹仟".isnumeric()
>>True
isidentifier 判断是否为python内部关键字或有效标志符
"def".isidentifier()
>>True
" is".isidentifier()
>>False
" ".isidentifier()
>>False
isprintable 判断是否可打印(包括空字符串)
"\b".isprintable()
>>False
"\t".isprintable()
>>False
"\n".isprintable()
>>False
isascii 判断是否为ascii码
"二".isascii()
>>False
"`".isascii()
>>True
"】".isascii()
>>False
查找元素位置
- find(start: SupportsIndex |None= …, end: SupportsIndex |None= …),查找某个元素在字符串中第一次出现的索引位置,不存在返回-1
start表示起始索引位置,end表示终止位置,左闭右开
c = 'adsadaasdd'
c.find('d',0)
>>1
c.find('d',3)
>>4
c.find('d',1)
>>1 #显示为1
- rfind(start: SupportsIndex |None= …, end: SupportsIndex |None= …),查找某个元素在字符串中最后一次出现的索引位置,不存在返回-1
start表示起始索引位置,end表示终止位置,左闭右开
c = 'adsadaasdd'
c.rfind('d',0)
>>9
c.rfind('d',3)
>>9
c.rfind('d',3,6)
>>4
c.rfind('d',3,9)
>>8 #不显示9,
count(a),用来统计字符串中某个元素的数量,不存在的则为返回0
str = 'adsada231ada'
num_a = str.count('a')
print(num_a)
>>5
首字母大写
- 使用内置的capitalize()函数
- 切片字符串然后使用upper()将单一字符变为大写再拼接
s1 = 'hello'
s1.capitalize()
print(s1)
s1 = s1[0].upper()+s1[1:]
print(s1)
>>Hello
s2 = 'hello world'
s2_arr = s2.split(" ")
new_str = f'{s2_arr[0].capitalize()} {s2_arr[1].capitalize()}'
print(new_str)
>>Hello World
格式化整数
format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’
使用方法由两种:b.format(a)和format(a,b)。
基本用法:
- 不带编号,即“{}”
- 带数字编号,可调换顺序,即“{1}”、“{2}”
- 带关键字,即“{a}”、“{tom}”
print('{} {}'.format('hello','world'))
>>hello world
print('{0} {1}'.format('hello','world'))
>>hello world
print('{1} {1} {0}'.format('hello','world'))
>>world world hello
print('{a} {tom} {a}'.format(tom='hello',a='world'))
>>world hello world
进击用法
- < (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐
- 取位数“{:4s}”、”{:.2f}”等
print('{} and {}'.format('hello','world'))
>>hello and world
print('{:10s} and {:>10s}'.format('hello','world'))
>>hello and world
print('{:^10s} and {:^10s}'.format('hello','world'))
>> hello and world
print('{} is {:.2f}'.format(1.123,1.123))
>>1.123 is 1.12
print('{0} is {0:>10.2f}'.format(1.123))
>>1.123 is 1.12
print('{:*>10.2f}'.format(1.123)) #右对齐,小数点后2位,不足的补*
>>******1.12
多个格式化
‘b’ - 二进制。将数字以2为基数进行输出。
‘c’ - 字符。在打印之前将整数转换成对应的Unicode字符串。
‘d’ - 十进制整数。将数字以10为基数进行输出。
‘o’ - 八进制。将数字以8为基数进行输出。
‘x’ - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
‘e’ - 幂符号。用科学计数法打印数字。用’e’表示幂。
‘g’ - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
‘n’ - 数字。当值为整数时和’d’相同,值为浮点数时和’g’相同。不同的是它会根据区域设置插入数字分隔符。
‘%’ - 百分数。将数值乘以100然后以fixed-point(‘f’)格式打印,值后面会有一个百分号。
print('{:d}'.format(20))
>>20
print("{:o}".format(20))
>>24
print("{:x}".format(20))
>>14
print('{:e}'.format(20))
>>2.000000e+01
print('{:g}'.format(20.1))
>>20.1
print('{:%}'.format(20))
>>2000.000000%
Print函数
用逗号分隔输出的字符串
print("a","b",sep=',')
>>a,b
输出字符串不换行
print('hello')
print('world')
>>hello
>>world
print('hello',end=' ')
print('world')
>>hello world
格式化
s = 'road'
d = len(s)
print('The length of %s is %d' % (s,d))
>>The length of road is 4
占位符
Template无疑是一个好东西,可以将字符串的格式固定下来,Template属于string中的一个类,所以要使用的话可以用以下方式调用:
有个特殊的标识符,它的使用具有以下的规则:它的主要实现方式为,它的使用具有以下的规则:它的主要实现方式为xxx,其中xxx是满足python命名规则的字符串,即不能以数字开头,不能为关键字等,如果xxx需要和其他字符串接触时,可用将xxx包裹起来,例如:例如,aaaxxx需要和其他字符串接触时,可用将xxx包裹起来,例如:aaa{xxx}aaa
from string import Template
s = Template('There is $a and ${b}s')
print(s.substitute(a='apple',b='banbana'))
print(s.safe_substitute(a='apple',b='banbana'))
>>There apple and banbanas
>>There apple and banbanas
还可以通过字典来传递数据
from string import Template
s = Template('There is $a and ${b}s')
d = {'a':'apple','b':'banbana'}
print(s.substitute(d))
>>There is apple and banbanas
注:substitute是一个严肃的方法,如果有key没有输入,那就一定会报错。虽然会很难看,但是可以发现问题。safe_substitute则不会报错,而是将$xxx直接输入到结果字符串中。
删除多余字符
strip
- lstrip
- rstrip
传递给lstrip/rstrip/strip的参数被视为一组字符
' spacious '.lstrip()
>>'spacious '
'www.example.com'.lstrip('cmowz.')
>>'example.com'
如果想删除一整个字符串,请使用replace或者切片来实现