python字符串操作总结_【Python】字符串操作总结

#字符串的长度

#len(str)

string='''123456789'''

strlen=len(string)

print(strlen)

#输出为 9

#将非字符串转换为字符串

#str()

nostr = 1.23

print(str(nostr))

#输出为 1.23

#将字符串转化为其他

#eval()

isstr='''123456'''

print(eval(isstr))

#输出为 123456

#进制转换

#hex(x) 整数转换为16进制

#oct(x) 整数转换为8进制

a=123

tohex=hex(a)

tooct=oct(a)

print(tohex)

print(tooct)

#输出为 0x7b

#输出为 0o173

#编码转换

#chr(u) 将unicode编码转换为单字符

#ord(x) 将字符转换为unicode编码

isonestr='是'

tochr=(isonestr)

print(tochr)

print(ord(tochr))

#输出为 0o173

# 是

#字符串处理功能

#str.lower() strupper()

#分别代表将字符串变为小/大写

engstr='A,B,Cd,Edf,s'

print(str.lower(engstr))

print(str.upper(engstr))

#输出为 a,b,cd,edf,s

#A,B,CD,EDF,S

#分割,将字符串变成数组

#要转换的字符串.split(分割符)

ashuzu=engstr.split(",")

#将字符串转换成数组,赋值给ashuzu

print(ashuzu[3])

#输出为 Edf

#字符串计数,统计该字符串中 某个字符出现的次数

print('在 this is a amazing question 字符串中 i出现的次数是'+str('this is a amazing question'.count("i")))

#输出为 在 this is a amazing question 字符串中 i出现的次数是4

#批量替换

print('在这段话中,将 旧 这个字符替换为 新 旧 旧 旧'.replace('旧','新'))

#输出为 在这段话中,将 新 这个字符替换为 新 新 新 新

#字符串居中处理

#str.center(总宽度,[两侧填充字符,必须为单个字符])

print('字符串居中'.center(20,"6"))

#输出为

#6666666字符串居中66666666

#删除字符中左/右侧的字符

#str.strip(chars)

print(',emm,这段话,去除一部分 = '.strip(" =,"))

#输出为emm,这段话,去除一部分

#字符串批量添加

#str.join(str1)

#在str1字符串中 除最后一个外,每个字符后面都添加一个str字符

print(','.join("123456"))

#输出为1,2,3,4,5,6

#字符串格式化

#str1.format()

#eg '{1} is {2} amazing {0 : 填充字符 对奇方式 宽度} !'.format('this','a','question')

# 默认排序为0→递增 当给大括号内赋值时,则按大括号内的数字的数字进行选择。

#填充字符须为单字符

#对齐方式:右对齐 ^居中对齐

# 例如 '{1} is {2} amazing {0} !'.format('this','a','question' :=>20)

print('{1:=>20} is {2} amazing {0} !'.format("this","a","question"))

#输出===================a is question amazing this !

#宽度为20,右对齐,填充字符为=

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值