#字符串的基本操作
#1、格式控制 与c语言基本一样 : %d %c %f %s %.2f 在匹配时 '%' 相当于 c语言中 ',' 的作用
str = 'hello %c,%d name is %s'
m_tuple = tuple(('w',1,'hexianmin'))
str % m_tuple
# 2、模板字符串 $后面的内容要紧跟着$ 不然会报错 使用substitute时 对应的关键字和值都要给出 要不然也会报错 就是要一一对应
from string import Template
tem = Template('hello ${key1},my name is $key2')
print(tem.substitute(key1='world',key2='hexianmin')) #key1 key2 的顺序无关紧要 主要是看关键字找
print(tem.safe_substitute(key1='world')) #但是使用safe_substitute时可以避免 如例
#3、format格式控制 1、默认顺序 2、指定索引值 3、利用关键字(key)找
from math import pi
import math
my_age = 'my age is {0},this is {value:.2f}' #注意区别 :.2f 与 %.2f 的使用情况
print(my_age.format('20',value = pi))
print( "an {} is {} and {}".format('apple','fruit','plant') )
print( "an {1} is {0} and {2}".format('appl
Python中的字符串(str)及其基本操作
最新推荐文章于 2023-02-22 20:06:14 发布