Python 字符串

本文主要总结字符串的知识点。

一、字符串格式化

字符串格式化使用百分号%来实现。

#字符串格式化一个值
hellosta = "hello,%s"
str = "susan"
print(hellosta % str)  #hello,susan

hellotwo = "hello,%s and %s"
names = ("su","jane")
names2 = ["su","jame"]
#只有元组和字典可以格式化一个以上的值
print(hellotwo % names) #hello,su and jane
print(hellotwo % names2) #TypeError: not enough arguments for format string

#%后面加上字典的键(用圆括号括起来),后面再跟上其他说明元素
dictnum = {'one':123,'two':234}
dictstr = "hello,%(two)s"%dictnum
print(dictstr) #hello,234

基本的转换说明符包括以下部分:

(1)%字符:标记转换说明符的开始。

(2)转换标志(可选):- 表示左对齐;+ 表示在转换值之前要加上正负号;“”(空白字符)表示正数之前保留空格;0表示转换值若位数不够则用0填充。

(3)最小字段宽度(可选):转换后的字符串至少应该具有该值指定的宽度。如果是*,则宽度从值元组中读出;

(4)点(.)后跟精度值(可选):如果转换的是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就表示最大字段宽度。如果是*,那么精度将会从元组中读出。

(5)转换类型:

例子:

#精度为2
p = '%.2f'%pi
print(p)  #3.14
#宽度为5
p2 = '%.5s'%'hello,world'
print(p2) #hello
#也可以用*表示精度和宽度
p3 = '%.*s'%(5,'hello,world')
print(p3) #hello

也可以使用模板字符串格式化--这个可以查看(Python 自动生成代码 方法二 )这篇文章。

 二、字符串方法

1、查找子串

find方法可以在一个较长的字符串中查找子串,它返回子串所在位置的最左端索引,如果没有找到则返回-1.

str = "hello,world.It started"
substr = 'world'
print(str.find(substr)) #6
nostr = 'su'
print(str.find(nostr)) #-1

2、大小写

str1 = "Hello,World.That`s All"
str2 = "hello,world.that`s all"
#小写
print(str1.lower()) #hello,world.that`s all
#大写
print(str2.upper()) #HELLO,WORLD.THAT`S ALL
#单词首字母大写,有点瑕疵
print(str2.title()) #Hello,World.That`S All
print(string.capwords(str2)) #Hello,world.that`s All

3、替换字符字符串

replace方法返回某字符串的所有匹配项均被替换之后得到字符串。

translate方法可以替换字符串中的某些部分,和replace方法不同的是,它只处理单个字符。

restr = "this is a cat.cat is lovely"
#restr.replace(old, new, count),count表示最多可以替换多少个字符串
print(restr.replace('cat', 'dog', 1)) #this is a dog.cat is lovely
#translate(table)
table = str.maketrans('it','ad')
print(restr.translate(table)) #dhas as a cad.cad as lovely

4、连接分割除空格

join方法用来连接序列中的元素;

split方法用来将字符串分割成序列;

strip方法返回去除两侧(不包括内部)空格的字符串;

seq = ['a','2','c','d']
sep = '+'
joinstr = sep.join(seq)
print(joinstr) #a+2+c+d
splitstr = joinstr.split('+')
print(splitstr) #['a', '2', 'c', 'd']
stripstr = "        !!hello world !! **   "
print(stripstr.strip()) #!!hello world !! **
print(stripstr.strip(' *!')) #hello world
原文地址:https://www.cnblogs.com/susan-su/p/10716962.html