【Python】不可变序列str常用操作

2018-08-23  本文已影响40人  Natsuka
申明转义字符
常用内置方法(不改变字符串变量本身)
x = "I am an apply!"
m = x.replace("apply","orange")
print(x) # 结果为:I am an apply!
print(m) # 结果为:I am an orange!
y = "hahahahaha"
n = y.replace("ha","he",3)
print(y) # 结果为:hahahahaha
print(n) # 结果为:hehehehaha
x = "poi01,116.446234,40.491201"
m = x.split(",")
print(x) # 结果为:'poi01,116.446234,40.491201'
print(m) # 结果为:['poi01', '116.446234', '40.491201']
y = ['poi01', '116.446234', '40.491201']
m = "-"
n = m.join(y)
print(n) # 结果为:'poi01-116.446234-40.491201'
数据格式转化
格式化字符
name = 'Apple'
print("%s is fruit." %name) # 结果为:Apple is fruit.
.format方法格式化
"User ID: {0}".format("root") # 结果为:'User ID: root'
"{} talk to {}".format("a","b") # 结果为:'a talk to b'
"{}{}{}".format("a","b","c") # 结果为:'abc'
"{0}{1}{2}{0}".format("a","b","c") # 结果为:'abca'
"{}{}{}{}".format("a","b","c") # 结果为:报错
"my job is a {career}".format(career="designer") 
# 结果为:"my job is a desinger"
x = "abc{}"
m = x.format("def")
print(x) # 结果为:abc{}
print(m) # 结果为:abcdef
"{:f}".format(4.123) #结果为:'4.123000'
"{:.2f}".format(4.123) #结果为:'4.12'
"{:e}".format(4.123) #结果为:'4.123000e+00'
"{:.0f}".format(99.6) #结果为:'100'
"{:%}".format(4.123) #结果为:'412.300000%'
"{:d}".format(10) #内部必须内整数
上一篇下一篇

猜你喜欢

热点阅读