Python(3)--字符串
Python(3)--字符串
字符串格式
字符串也是不可变的
# 元组匹配字符串格式
>>> format = "hello %s."
>>> values('world')
>>> values = ('world')
>>> format % values
'hello world.'
# 使用字符串模板的情况
from string import Template
def main():
str_trmp = Template('Hello $who.')
res = str_trmp.substitute(who="tom")
print(res)
if __name__ == '__main__':
main()
# 字符串格式化的最简形式{}占位符
>>> "{},{} and {}".format("first","second","third")
'first,second and third'
>>> "{2},{1},{0}".format("1","2","3")
'3,2,1'
>>>
from math import pi
from math import e
def main():
# 两位精度
print("{name} is approximately {value:.2f}.".format(value=pi, name="pai"))
# 默认浮点精度
print("{name} is approximately {value}.".format(value=pi, name="pai"))
# f简写赋值
print(f"Euler's value is {e}.")
if __name__ == '__main__':
main()
基本说明
基本思想是字符串调用format(),并提供要设置格式的值,{}包裹的是要替换的字段
替换的字符串可能包含一下这几个部分(均是可选的)
- 字段名:索引或者标识符,指出那个字符串用于替换
- 转换标识符:在叹号后的单个字符,例如r(repr),s(str),a(ascii)
- 格式说明符 L如.2f
替换字段名
# 未命名字段按顺序替换,或者依照命名的字段替换
>>> "{foo} {} {bar} {}".format(1,2,bar=4,foo=3)
'3 1 4 2'
# 仅访问数据的部分
>>> username = ['Chirs','arusk']
>>> "Mr {name[1]}".format(name=username)
'Mr arusk'
import math
def main():
str = "the {mod.__name__} module defines the value {mod.pi} for PI"
res = str.format(mod=math)
print(res)
if __name__ == '__main__':
main()
转换
# 字符串,字面量,ascii值
>>> print("{str!s} {str!r} {str!a}".format(str="a"))
a 'a' 'a'
# 整数
>>> "The number is {num}".format(num=20)
'The number is 20'
# 浮点
>>> "The number is {num:f}".format(num=20)
'The number is 20.000000'
# 浮点型
>>> "The number is {num:b}".format(num=20)
'The number is 10100'
精度与宽度
# 设置宽度 字符和数字的对齐方式不一样
>>> "{num:10}".format(num=3)
' 3'
>>> "{str:10}".format(str="aaa")
'aaa '
# 设置精度
>>> "PI {pi:.2f}".format(pi=pi)
'PI 3.14'
# 千分位分隔符
>>> 'money is {:,}'.format(10**6)
'money is 1,000,000'
格式对齐与填充
# 0填充
>>> '{:010.2f}'.format(pi)
'0000003.14'
# 左对齐 居中 右对齐
>>> print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}'.format(pi))
3.14
3.14
3.14
# 指定字符填充
>>> "{:$^15}".format("Hello")
'$$$$$Hello$$$$$'
# 指定符号与数字间填充
>>> print('{0:10.2f}\n{1:=10.2f}'.format(pi,-pi))
3.14
- 3.14
# 正数添加符号
>>> print('{0:+.2f}\n{1:+.2f}'.format(pi,-pi))
+3.14
-3.14
# 字符前缀
>>> "{:#b}".format(12)
'0b1100'
# 保留小数点
>>> "{:#g}".format(20)
'20.0000'
def main():
width = int(input('Please input width: '))
price_width = 10;
item_width = width = price_width;
header_fmt = '{{:{}}}{{:>{}}}'.format(item_width,price_width)
fmt = '{{:{}}}{{:>{}.2f}}'.format(item_width,price_width)
print('=' * width)
print(header_fmt.format('Item','Price'))
print('-' * width)
print(fmt.format('Apple',0.4))
print(fmt.format('Orange',0.5))
print(format('Dried Apricots (16 oz.)'),9)
print('=' * width)
if __name__ == '__main__':
main()
字符串方法
# 居中center
>>> "Hello world".center(39)
' Hello world '
>>> "Hello world".center(39,"*")
'**************Hello world**************'
# 返回子串的第一个索引位置find()
>>> "aaa aaa aa a aaaa".find('aaa')
0
# 指定起点find('',start,end)
>>> 'aaa bb aaa'.find('aaa',1)
7
# 给字符串添加分隔符join()
>>> sep = '+'
>>> seq = ['1','2','3']
>>> sep.join(seq)
'1+2+3'
# 转小写lower
>>> 'HELLO'.lower()
'hello'
# 替换字符串replace()
>>> 'Hello Tom'.replace('Tom','Alice')
'Hello Alice'
# 分割字符串,拆分成序列split()
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
# 删除字符串两边的空白符strip()
>>> ' hello world '.strip()
'hello world'
# 指定删除的字符
>>> '******Hi,**** to * every***one!'.strip('*!')
'Hi,**** to * every***one'

浙公网安备 33010602011771号