欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python3字符串操作

程序员文章站 2022-04-09 17:36:57
python3字符串操作 ......

python3字符串操作

1 x = 'abc'
2 y = 'defgh'
3 
4 print(x + y)         #x+y
5 print(x * 3)         #x*n
6 print(x[2])         #x[i]
7 print(y[0:-1])         #str[i:j]
8         

 

 

#求长度
>>> len(x)
11
#将其他类型转换为字符串
>>> str(123)
'123'
#将数字转为对应的utf-8字符
>>> chr(97)
'a'
#将字符转为对应的数字
>>> ord('a')
97
#将数字转为16进制
>>> hex(32)
'0x20'
#将数字转为8进制
>>> oct(32)
'0o40'

 

 1 >>> str = 'abdcsdsjfkasfdfja'
 2 #将所有字符转为小写
 3 >>> str.lower()
 4 'abdcsdsjfkasfdfja'
 5 #将所有字符转为大写
 6 >>> str.upper()
 7 'abdcsdsjfkasfdfja'
 8 #判断所有字符是否为小写
 9 >>> str.islower()
10 false
11 #判断所有字符是否都为可打印的
12 >>> str.isprintable()
13 true
14 #判断所有字符都是数字
15 >>> str.isnumeric()
16 false
#判断是否以参数为结尾
>>> str.endswith('fja')
true
#判断是否以参数为开头
>>> str.startswith('asd')
false
#将字符串以sep为分隔符分开, 返回一个列表
>>> str.split(sep='a')
['', 'bdcsdsjfkasfdfj', '']
>>> str.split(sep='s')
['abdc', 'd', 'jfka', 'fdfja']
#返回参数串的个数
>>> str.count('sd')
1
#将第一个参数字符串替换为第二个参数字符串,替换前n个
>>> str.replace('s', 'c', str.count('s'))
'abdccdcjfkacfdfja'
#center就是居中的意思,字符串的长度为6个单位,tj 占了两个单位,其余的位子用$来占位

>>>str ='tj'

>>>print ( str.center(6, '$'))

>>>$$tj$$

#从原字符串左右俩侧 删掉字符串列出的字符
>>> str.strip('sdffa')
'bdcsdsjfkasfdfj'
>>> str.strip('sdffafjdb')
'csdsjfkasfd'

#长度不够左侧用0填充
>>> str.zfill(23)
'000000abdcsdsjfkasfdfja'

#join中参数的每一个元素用':'连起来
>>> ':'.join(['127.0.0.1', '9988'])
'127.0.0.1:9988'