#字符串的基本操作
#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('apple','fruit','plant') )
print("{foo} {} {bar} {}".format(6,2,bar=4,foo=3)) #注意手动编号和自动编号不可以同时使用
print( 'the {mod.__name__} module defines the value {mod.pi} for PI1'.format(mod=math) ) #format替换后可以识别{math.__name__} 和 {math.pi}
#4、format :f 浮点数 :10.2 整数部分代表宽度(数字靠右对其 字符串靠左对齐)小数部分代表小数位数 :, 代表千位分隔符
"{:,}".format(10**10) # :, 代表千位分隔符
print('{0:~<10.2f}\n{0:$^10.2f}\n{0:>010.2f}'.format(pi)) # < 左对齐 > 右对齐 ^ 居中 整数10代表整个宽度 10前面的0为剩余长度前面补0 还可以指定字符填(紧跟:后面)充
print('{0:=10.2f}'.format(-pi)) # = 将填充字符串放在符号和数字之间
print('{:#b}'.format(142))
#5、字符串的方法
#1、center 两个参数 其他函数:ljust(字符串左对齐,用指定字符填充剩余长度) rjust(字符串右对齐,用指定字符填充剩余长度) zfill(方法返回指定长度的字符串,原字符串右对齐,前面填充0)
test_str = "my name is hexianmin"
test_str.center(59,'-')
#2、find 在字符串中找指定字符串 找到后返回字符串第一个字符的下标 找不到返回-1 区别与in in只检查单个字符是否包含在字符串中
ss0 = 'my name is$$$ hexianmin$$$'
ss0.find('$$$',0,23) #只找第一个字符 还可以指定寻找范围 与切片一样 后面的23取不到
#其他字符方法:rfind index rindex count startswith('ssa',0,5) 指定字符串开头 endswith 指定字符串结尾
#3、join 将字符串(或者列表)用指定字符连接起来 和 split相反
print('-'.join(list("czcs")))
#4、lower() upper() 不改变调用该方法的字符串本身
ss2 = 'cdsvdCS'
print(ss2.lower().islower()) #islower() 检查是否为小写 返回 True False
ss2.upper()
#5、replace('str1','str2') 替换指定字符串 全部替换
ss3 = 'is my apple is my love'
ss3.replace('is','are')
#6、split 指定字符串拆分 拆分后为序列!!!
print("1+2+3+4+5+6".split('+'))
#7、strip 将字符串开头和结尾的空白(不包括中间的空白)删除 并返回删除后的结果 其他方法:lstrip rstrip
' fs df '.strip()
'*** sdgd * for dvdf!!!***'.strip('*!f') #还可以指定删除哪些开头和结尾的字符 当指定时 默认删除空白将失效!!!
#8、translate 只可以一个字符一个字符的转换
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab) #maketrans 在python3中不用导入 直接用str调用即可
str = "this is string example....wow!!!"
print(str.translate(trantab))