字符串基本操作
所有标准序列操作(索引、切片、乘法、成员资格检查、长度、最小值、最大值)都适用于字符串,字符串时不可变的,因此所有的元素 赋值都是非法的。
设置字符串的格式
将值转换为字符串并设置其格式是一个重要的操作,需要考虑众多不同的需求,因此随着时间的流逝,Python提供了多种字符串格式设置方法。之前,主要解决方案是使用字符串格式设置运算符-%。这个运算符的行为类似与C语言中的经典函数printf:在%左边指定一个字符串,并在右边指定要设置其格式的值。指定要设置其格式的值,可使用单个值,可以使用元组,还可以使用字典。其中最常用的就是元组。
format="hello,%s. %s enough for ya?"
values=('world','hot')
print(format % values)
hello,world. hot enough for ya?
Process finished with exit code 0
下边这种格式设置方法现在依然管用,且依然活跃在众多代码中。
from string import Template
tmp1=Template("hello,$who $what enough for ya")
print(tmp1.substitute(who='jin',what='run'))
hello,jin run enough for ya
Process finished with exit code 0
下边,编写新代码时,选择使用字符串方法format,它融合强化了早起方法的有点。
print("{},{} and {}".format("first","second","third"))
print("{0},{1} and {2}".format("first","second","third"))
print("{1},{0},{3},{2},{5},{4}".format("long","how","i","will","you","love"))
from math import pi
print("{name} 大约是 {value:.3f}".format(value=pi,name='pi'))
# 指定了格式说明符.2f,并使用冒号将其与字段名隔开。它意味着要使用包含2位小数的浮点数格式。
print("{name} 大约是{value}".format(name='pi',value=pi))
first,second and third
first,second and third
how,long,will,i,love,you
pi 大约是 3.142
pi 大约是3.141592653589793
Process finished with exit code 0
还有一种简写。在这种情况下,使用f字符串,在字符串前边加上f
from math import e
print(f"e的值大约是{e}")
e的值大约是2.718281828459045
Process finished with exit code 0
设置字符串的格式(完整版)
替换字段名
print("{foo} {} {bar} {}".format(1,2,bar=4,foo=5))
print("{how} {} {} {you}".format(2,1,how=5,you='?'))
5 1 4 2
5 2 1 ?
Process finished with exit code 0
并不是使用值的全部,也可以使用值的一部分:
fullname=["motor","ruola"]
print("Mr {name[1]}".format(name=fullname))
print("Mr {name[0]}".format(name=fullname))
Mr ruola
Mr motor
Process finished with exit code 0
基本转换
可以指定要转换的值是那种类型
print("the number is {num}".format(num=42))
print("the number is {num:f}".format(num=42))
print("the number is {num:b}".format(num=42))
the number is 42
the number is 42.000000
the number is 101010
Process finished with exit code 0
类型 | 含义 |
---|---|
b | 将整数表示为二进制数 |
c | 将整数解读为Unicode |
d | 将整数视为十进制进行处理,这是整数默认使用的说明符 |
e | 使用科学计数法来表示小数 |
E | 与e相同,但使用E来表示小数 |
f | 将小数表示为定点数 |
F | 与f相同 |
g | 自动在定点表示法和科学表示法之间作出选择。默认用于小数的说明符, |
G | 与g相同,但使用大写来表示指数和特殊值 |
n | 与g相同,但插入随区域而异的数字分隔符 |
o | 将整数表示为八进制数 |
s | 保持字符串的格式不变,默认用于字符串的说明符 |
x | 将整数表示为十六进制并使用小写字母 |
X | 与x相同,但使用大学字母 |
% | 将数表示为百分比 |
宽度、精度和千位分隔符
from math import pi
print("pi day is {pi:.2f}".format(pi=pi))
pi day is 3.14
Process finished with exit code 0
符号、对齐和用0填充
字符串格式设置事例
width=int(input('please enter width'))
price_width=10
item_witdth=width-price_width
header_fmt='{{:{}}}{{:>{}}}'.format(item_witdth,price_width)
fmt='{{:{}}}{{:>{}.2f}}'.format(item_witdth,price_width)
print('='* width)
print(header_fmt.format('item','price'))
print('-'* width)
print(fmt.format('apple',0.4))
print(fmt.format('pears',0.5))
print(fmt.format('food',1.43))
print(fmt.format('watermelon',1.43))
print(fmt.format('clothes',888))
print('=' * width)
please enter width40
========================================
item price
----------------------------------------
apple 0.40
pears 0.50
food 1.43
watermelon 1.43
clothes 888.00
========================================
Process finished with exit code 0
字符串方法
字符串的方法要多得多,因为其很多方法都是从模块string哪里继承来的。
center
方法center通过两边添加填充字符让字符串居中
print("how long will i love you ?".center(50))
print("how long will i love you ?".center(50,'*'))
how long will i love you ?
************how long will i love you ?************
Process finished with exit code 0
find
方法find在字符串中查找子串。如果找到,就返回子串的索引,否则返回-1
print("how long will i love you,as long as stars above you".find('as'))
word="how long will i love you, as long as you want me to"
print(word.find('me'))
print(word.find('how'))
print(word.find('no'))
25
46
0
-1
Process finished with exit code 0
指定搜索的起点和终点
word="as long as you want me to"
print(word.find('as'))
print(word.find('as',1))
print(word.find('as',1,9))
0
8
-1
Process finished with exit code 0
join
join是一个非常重要的字符串方法,其作用与split相反,用于合并序列的元素
queue=['1','2','3','4','5']
queue2='+'
print(queue2.join(queue))
dir='','etc','httpd','httpd.config'
print('/'.join(dir))
print('C:'+ '\\'.join(dir))
1+2+3+4+5
/etc/httpd/httpd.config
C:\etc\httpd\httpd.config
Process finished with exit code 0
lower
方法lower返回字符串的小写版本
print('HOW LONG WILL I LOVE YOU'.lower())
name='SB'
names=['sb','sB','sa','SA']
if name.lower() in names:print('ok')
else:print('false')
how long will i love you
ok
Process finished with exit code 0
replace
方法replace将指定子串替换为另一个字符串,并返回替换后的结果。
print('how long will i love you ,as long as stars above you'.replace('as','?'))
how long will i love you ,? long ? stars above you
Process finished with exit code 0
split
split是一个非常重要的字符串方法,其作用与join相反,用于将字符串拆分为序列。
print('1+2+3+4+5'.split('+'))
print('/usr/local/logs'.split('/'))
['1', '2', '3', '4', '5']
['', 'usr', 'local', 'logs']
Process finished with exit code 0
strip
方法strip将字符串开头和末尾的空白删除,并返回删除后的结果。
print(' how long will i love you '.strip())
name=' energetic '
names=['energetic','energy','dreamming']
# if name in names : print('ok')
if name.strip() in names :print('ok')
else: print('false')
how long will i love you
ok
Process finished with exit code 0
translate
方法translate与replace一样替换字符串的特定部分,但不同的是它只能进行单字符替换,这个方法的优势在于能够同时替换多个字符,因此效率比replace高。
总结
- 字符串格式设置:求模运算符可用于将值合并为包含转换标志的字符串,这能够让你以众多方式设置值的格式,入左对齐或右对齐,指定字段宽度和精度,添加符号以及在左边填充0
- 字符串方法:例如split 、join。