字符串格式化,单独拿出来说就是与数值格式化相同,但常用如日常字符串的输出
如:
>>> price=100
>>> print("the book's price is %s" % price)
the book's price is 100
#其中字符串中的%s 是占位符,%是分割符,price对应的是%s位置的值。
多个变量:
>>> price=500
>>> name="book"
>>> print("the %s's price is %s" %(name,price))
返回
the book's price is 500
其他占位符:
d,i 带符号十进制整数
o 带符号八进制整数
x/X 带符号十六进制整数
e/E 科学计数法
f/F 十进制浮点
g/G 只能选择是e还是f格式
C转化为单字符(只接受整数或单字符字符串)----暂时不知道作用
r 使用repr()方法转换为字符串,上边已经使用过
s 使用srt()转化为字符串
输出格式例子
print("num is :%06d" % num) 红色部分 同数值 部分可是用法相同 参见https://mp.youkuaiyun.com/postedit/89705977
字符串的大小写转换
title()#单词首字母大写
lower()#全部小写
upper()#全部大写
strip()#删除前后空格
lstrip() #删除左侧空格
rstrip() #删除右侧空格
startswith()#判断开头字符串
endswith() #判断结尾字符串
find()#返回字符串位置,没有找到返回-1,可以带参数 a.find("acd",9)从索引9开始查找 字符串acd
index()#同上差不多,但是如果没找到就会引发错误。
replace()#使用指定字符串替换目标字符串。replace('a','b',1),1表示更换第几个a,如不加此参数默认全部更换
translate() #使用指定的翻译映射表对字符串执行替换。作用不太明显,需要记住映射表。可用maketrans()代替
table=str.maketrans('abc','123') print(table)---->{97:49,98:50.99:51} 自动将abc的编码分别对应到了123上。
split()#将指定字符串分割成序列
a='crazyit.org is a good site'
print(s.split()) #输出['crazyit.org','is','a','good','site']
print(s.split('.') #查找 '.'的位置进行分割
print(s.split(None,2)) #输出以空格为分割,只分割两个,['crazyit.org','is','a good site']
jion() #链接字符串
'/'.jion(X) #其中'/'是链接符