python-2 str
字符串
0x31 ==> 0011 0001 49
0x41 ==> 0100 0001 65
0x61 ==> 0110 0001 97
a = 'abc'
a = f'{a}+++' # 差值 3.6版本以上
a ## 'abc+++'
range(5) # 惰性
range(0, 5)
list(range(5)) # 立即
[0, 1, 2, 3, 4]
map(str, range(5)) # 惰性,可迭代对象
<map at 0x14ab30181c8>
b = R'c:\windos\nt'
":".join(b) # 用 : 连接 b 中的每一个字符
'c:::\\:w:i:n:d:o:s:\\:n:t'
",".join(map(str, range(5))) # join后必须是str
'0,1,2,3,4'
'x y'.split() # 至少一个空白字符,如果连续,认作一个,立即返回一个列表
['x', 'y']
'x \t \r\n y'.split()
['x', 'y']
'x \ta \r\n y'.split('a')
['x \t', ' \r\n y']
'x \ta \r\n y'.split('x ') # 不支持正则表达式
['', ' \ta \r\n y']
"a b c ".rsplit(maxsplit=1) # 从右边开始切 maxsplit 切几次
['a b', 'c']
'a\nb\r\nc\rd\te'.split()
['a', 'b', 'c', 'd', 'e']
"""\
a
b
c
""".splitlines() # 开头三引号后加反斜线 ,否则多切出一段
['a', 'b', 'c']
'a\n\nb\r\n\r\nc\rd\te'.splitlines()
('a', ' ', ' b')
'a b'.partition('t') # 特殊例子 切割符
('a b', '', '')
'abc'.upper().lower() # upper 统一转大写 lower 统一转小写
'abc'
"abC".swapcase() #大小写转换
'ABc'
str.upper('abc') , 'abc'.upper()
('ABC', 'ABC')
'user-agent'.capitalize() # 首字母大写
'User-agent'
'user-agent abc'.title()
'User-Agent Abc'
"abc".center(20,'0')
'00000000abc000000000'
"abc".ljust(20)
'abc '
"abc".rjust(20,"0")
'00000000000000000abc'
"abc".zfill(20)
'00000000000000000abc'
"www.magedu.com".replace('www','abc')
'abc.magedu.com'
'x y'.replace(' ',' ')
'x y'
' \n a bc \t '.strip() # 默认拿掉字符串两端的所有空白字符
'a bc'
' \n a bc \t '.strip(' ')
'\n a bc \t'
' \f i am very very very sorry\t\r\n '.strip('\f\t\n\r yiar')
'm very very very so'
' \f i am very very very sorry\t\r\n '.strip('\f\t\n\ryiar')
' \x0c i am very very very sorry\t\r\n '
'\t a bc\r\ndef bc'.index('bc',5) # 找不到时,返回ValueError
12
'\t a bc\r\ndef bc'.count('bc') # 返回找到几个 没找到时返回0 不报错
2
'\t a bc\r\ndef bc'.find('abc') # 没有找到时,返回 小于零的数
-1
'%s, %-20d' % (2, 30)
'2, 30 '
'%05d' % 20 # 编写序号时 补位对齐使用 0(占位符) 5(宽度)
'00020'
'%3.5f' % (3 ** 0.5 ,) # 3 控制宽度 .5 控制精度
'1.73205'
'{0}'.format(list(range(5)))
'[0, 1, 2, 3, 4]'
'{0[4]}'.format(list(range(5)))
'4'
from collections import namedtuple
Student = namedtuple('Stu','name age')
tom = Student('tom', 20)
"{}".format(tom)
"Stu(name='tom', age=20)"
"{0.name} is {0.age}".format(tom) # 不使用
'tom is 20'
"{} is {}".format(tom.name, tom.age, tom)
'tom is 20'
ip = [192, 168, 1, 127]
"{} {} {} {}".format(*ip) # *ip 192, 168, 1, 127
'192 168 1 127'
"{:x} {{{}}} {:#x} {:#X}".format(*ip)
'c0 {168} 0x1 0X7F'
x = 2 ** 0.5
"{}".format(x)
'1.4142135623730951'
"{:.3f}".format(x)
'1.414'
"{:^20.2}".format(x)
' 1.4 '
"{:*^20.2}".format(x)
'********1.4*********'
"{:4.4%}".format(x)
'141.4214%'
"{:e}".format(x)
'1.414214e+00'
"{:2}".format(x)
'1.4142135623730951'
"{:.2}".format(x)
'1.4'