字符串操作

split() 从左切

'a  b'.split(' ')   # 有空串
------------------------------
['a', '', 'b']
'a  b'.split()
------------------------------
['a', 'b']
'a  b'.split(maxsplit=1)  #  maxsplit=1 切一刀
------------------------------
['a', 'b']
'a  b'.split(' ',maxsplit=1)
------------------------------
['a', ' b']
'a  b'.split(' ',maxsplit=2)    #有空串
------------------------------
['a', '', 'b']

rsplit() 从右切

'a  b'.rsplit(' ')   # 从右边向左切,只是切的时候从右边,返回的结果的顺序是不变的
------------------------------
['a', '', 'b']
'a  b'.rsplit(' ',maxsplit=1) 
------------------------------
['a ', 'b']
'a  b'.rsplit(' ',1) 
------------------------------
['a ', 'b']

splitlines() 按行切

'a  \t b\nc d\re f\nghi\r\nok'.splitlines() 
['a  \t b', 'c d', 'e f', 'ghi', 'ok']
'a  \t b\nc d\re f\nghi\r\nok'.splitlines(True)   # 保留切割符号\n
------------------------------
['a  \t b\n', 'c d\r', 'e f\n', 'ghi\r\n', 'ok']
'a  \t b\nc d\re f\nghi\r\n\r\nok'.splitlines() 
------------------------------
['a  \t b', 'c d', 'e f', 'ghi', '', 'ok']
s1 = '''1 hello
2 word'''
s1.splitlines(True)
------------------------------
['1 hello\n', '2 word']
s1 = '''1 hello
2 word'''
s1.splitlines()
------------------------------
['1 hello', '2 word']

partition() 保留切割符 ,只切割一刀,从左切

结果是 三元组,必须指定切割符

'a b'.partition()
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-21-bc9d6a73e428> in <module>
----> 1 'a b'.partition()


TypeError: partition() takes exactly one argument (0 given)
'a b'.partition(' ')
------------------------------
('a', ' ', 'b')
'a,b'.partition(',')
------------------------------
('a', ',', 'b')
'a,b,c'.partition(',')  #结果只是 三元组
------------------------------
('a', ',', 'b,c')

rpartition() 保留切割符 ,只切割一刀,从右切

结果是 三元组,必须指定切割符

'a,b,c'.rpartition(',')  #结果只是 三元组  rsplit(',', 1)
------------------------------
('a,b', ',', 'c')
'a,b,c'.rpartition(' ') 
------------------------------
('', '', 'a,b,c')
'a,b,c'.partition(' ') 
------------------------------
('a,b,c', '', '')
'a,b,c'.partition('s') 
------------------------------
('a,b,c', '', '')
'a,b,c'.rpartition('s') 
------------------------------
('', '', 'a,b,c')
'a,b,c'.partition()  # 必须要指定分割符,否则抛异常
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-222-1686eabb5889> in <module>
----> 1 'a,b,c'.partition()  # 必须要指定分割符,否则抛异常


TypeError: partition() takes exactly one argument (0 given)

字符串大小转换

  • upper() # 全部大写
  • lower() # 全部小写
  • swapcase() # 大小写切换
  • title() # 单词首字母大写
  • capitalize() # 句首字母大写

upper() 全部大写

s1 = 'Abc'
s1.upper()
------------------------------
'ABC'

lower() 全部小写

s1 = 'Abc'
s1.lower()
------------------------------
'abc'

swapcase() 大小写切换

s1 = 'Abc'
s1.swapcase()
------------------------------
'aBC'

title() 单词首字母大写

s1 = 'a list of string'
s1.title()
------------------------------
'A List Of String'

capitalize() 句首字母大写

s1 = 'a list of string'
s1.capitalize()
------------------------------
'A list of string'

center() 返回指定宽度的字符串并举中

S.center(width[, fillchar]) -> str
可以指定填充的字符, 只能指定一个,不能指定多个

s1 = 'abc'
s1.center(20)
------------------------------
'        abc         '
s1 = 'abc'
s1.center(20,'-')
------------------------------
'--------abc---------'
s1 = 'abc'
s1.center(20,'-@')  # 指定多个填充字符串会报错
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-215-2da7a7b823b6> in <module>
        1 s1 = 'abc'
----> 2 s1.center(20,'-@')  # 指定多个填充字符串会报错


TypeError: The fill character must be exactly one character long

zfill() 左端填充 '0'

S.zfill(width) -> str
需要指定填充的个数

s1 = 'abc'
s1.zfill(20)
------------------------------
'00000000000000000abc'

rjust() 右对齐(需要指定宽度)

S.rjust(width[, fillchar]) -> str
Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space).
可以指定填充的字符,默认是用空格填充

s1 = 'abc'
s1.rjust(20)
------------------------------
'                 abc'
s1 = 'abc'
s1.rjust(20,'*')
------------------------------
'*****************abc'

ljust() 左对齐(需要指定宽度)

S.ljust(width[, fillchar]) -> str
Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space).
可以指定填充的字符,默认是用空格填充

s1 = 'abc'
s1.ljust(10)
------------------------------
'abc       '
s1 = 'abc'
s1.ljust(10,'=')
------------------------------
In [31]: s1 = 'abc'                                                                                                 
In [32]: s1.ljust(10,'=')                                                                                           
Out[32]: 'abc======='

字符串的 '修改' *

replace()

不支持正则表达式

s2 = 'www.xxx.com'
s2.replace('w','p')
------------------------------
'ppp.magedu.com'
s2 = 'www.xxx.com'
s2.replace('w','p',2)
------------------------------
'ppw.magedu.com'
s2 = 'www.xxx.wwww'
s2.replace('ww','p')
------------------------------
'pw.xxx.pp'
s2 = 'www.xxx.wwww'
s2.replace('www.xxx.wwww','').split()   # 空串 '' 也是字符串
------------------------------
[]

注意返回结果的类型,是什么类型就调用什么了类型的方法,返回None不能调用任何方法
所以我们比较安全的方法是,一步一步的操作

关于不同返回结果操作的示例 1

'www.xxx.wwww'.replace('w','p')  # 返回的是一个新的字符串,后面就可以调用字符串的方法
------------------------------
'ppp.xxx.pppp'
s2 = 'www.xxx.wwww'
s2.replace('w','x').split('.')
------------------------------
['xxx', 'xxx', 'xxxx']
s2 = 'www.xxx.wwww'
s2.replace('w','x').split('.').replace()   # s2.replace('www.xxx.wwww','').split() 返回的是列表类型,不能调用字符串的replace方法
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-99-9ec78852aeb2> in <module>
        1 s2 = 'www.xxx.wwww'
----> 2 s2.replace('w','x').split('.').replace()   # s2.replace('www.xxx.wwww','').split() 返回的是列表类型,不能调用字符串的replace方法


AttributeError: 'list' object has no attribute 'replace'
s2 = 'www.xxx.wwww'
s2.replace('w','x').split('.').append('scm')  
# s2.replace('www.xxx.wwww','').split() 返回的是列表类型,可以调用列表的append方法,但是append()方法返回的是 None 类型
s2 = 'www.xxx.wwww'
s2.replace('w','x').split('.').append('scm').append('mxy')  
# s2.replace('www.xxx.wwww','').split() 返回的是列表类型,可以调用列表的append方法,
# 但是append()方法返回的是 None 类型,不能再调用 append()方法
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-103-fa3caebbd6c0> in <module>
        1 s2 = 'www.xxx.wwww'
----> 2 s2.replace('w','x').split('.').append('scm').append('mxy')
        3 # s2.replace('www.xxx.wwww','').split() 返回的是列表类型,可以调用列表的append方法,
        4 # 但是append()方法返回的是 None 类型,不能再调用 append()方法


AttributeError: 'NoneType' object has no attribute 'append'
s2 = 'www.xxx.wwww'
lst = s2.replace('w','x').split('.')
lst.append('scm')
lst
# s2.replace('www.xxx.wwww','').split() 返回的是列表类型,可以调用列表的append方法,
# 但是append()方法返回的是 None 类型,不能再调用 append()方法
------------------------------
['xxx', 'xxx', 'xxxx', 'scm']

关于不同返回结果操作的示例 2

'x y'.replace(',',' ').split()
------------------------------
['x', 'y']
'x y'.replace(',',' ').split().append('z')
------------------------------
In [34]: a = 'x y'.replace(',',' ').split().append('z')                                                             
In [35]: print(a)                                                                                                   
None
lst1 = 'x y'.replace(',',' ').split()
lst1.append('z')
lst1
------------------------------
['x', 'y', 'z']

strip(chars)

去掉指定的字符,从两边匹配字符集合中的任意一个,匹配到任意一个就去掉
如果遇到第一个非指定的字符,就停止操作
默认是去掉两边的空白字符, strip() 是最常用的,回车换行也看作是空格

'  I am a student \t\r\n '.strip()
------------------------------
'I am a student'
'  I am a student \t\r\n '.strip(' ')
------------------------------
'I am a student \t\r\n'
'  I am a very very very sorry  '.strip(' ')
------------------------------
'I am a very very very sorry'
'  I am a very very very sorry  '.strip('I')
------------------------------
'  I am a very very very sorry  '
'  I am a very very very sorry  '.strip(' I')
------------------------------
'am a very very very sorry'
'  I am a very very very sorry  '.strip('I ')
------------------------------
'am a very very very sorry'
'  I am a very very very sorry  '.strip('Ivery')
------------------------------
'  I am a very very very sorry  '
'  I am a very very very sorry  '.strip('Ive ry')
------------------------------
'am a very very very so'

lstrip()

功能同 strip(),但是只是对字符串左端操作

'  I am a very very very sorry  '.lstrip('Ive ry')
------------------------------
'am a very very very sorry  '

rstrip()

功能同 strip(),但是只是对字符串右端操作

'  I am a very very very sorry  '.rstrip('Ive ry')
------------------------------
'  I am a very very very so'

字符串的查找 *

index() 从左向右查找,返回的是最低位置的索引

在指定区间 [start ,end),从左到右,查找子串 sub,找到返回索引,没找到抛出异常。

S.index(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,

可以指定区间,但是要注意超界问题

s1 = 'I am very very very sorry'
s1.index('v')
------------------------------
5
s1.index('v', 5)
------------------------------
5
s1.index('v', 6, 11)
------------------------------
10
s1.index('v', 6, 8)  # 找不到直接抛异常
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-139-a70f19598007> in <module>
----> 1 s1.index('v', 6, 8)  # 找不到直接抛异常


ValueError: substring not found

rindex() 也是从左向右查找,返回的是最高位置的索引

在指定区间 [start ,end),从左到右,查找子串 sub,找到返回索引,没找到抛出异常。
S.rindex(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.

s = 'I am very very very sorry'
s.rindex('very')   # 最右边的"very"的 "v" 的索引是 15
------------------------------
15

s.rindex('very',10) # 最右边的"very"的 "v" 的索引是 15
------------------------------
15

s.rindex('very',10, 16)  # 索引从[10 ,16)的字符串是" very "最右边的"very"的 "v" 的索引是 10
------------------------------
10

s.rindex('very',-10, -1)  # -1 是结尾的意思
------------------------------
15

s.rindex('I',0,1)
------------------------------
0

find() 从字符串的左边找指定的子字符串,返回匹配到的第一个子字符串的索引值

S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.

1 返回负索引,表示找不到,找不到不会像 index()那样抛异常
2 返回正数说明一定存在
3 返回 0 说明正好在开头
4 使用 in 的时候一般不能指定区间,in通过切片也可以指定区间,但是用到切片会有内存的复制,所以这里不推荐使用in的时候指定区间,而是使用 find()
5 索引区间一定是从左向右划分的,也就是 stop 的值要大于 start 的值,否则找不到(返回 -1)

s1 = 'I am very very very sorry'

s1.find('v')
------------------------------
5

s1.find('very')
------------------------------
5

s1.find('v',6)
------------------------------
10

s1.find('v',6,11)
------------------------------
10

s1.find('v',6,10)
------------------------------
-1

s1.find('v',7,10)
------------------------------
-1

s1.find('v',7,-1)   # 区间指定 -1 表示字符串的结尾
------------------------------
10

rfind() 从字符串的右边找指定的子字符串,返回匹配到的第一个子字符串的索引值

S.rfind(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.

索引区间一定是从左向右划分的,也就是 stop 的值要大于 start 的值,否则找不到(返回 -1)

s1 = 'I am very very very sorry'

s1.rfind('v',6,11)
------------------------------
10

s1.rfind('v',5,11)
------------------------------
10

s1.rfind('v',-10,-1)    # 区间指定 -1 表示字符串的结尾,返回的索引值可是从0开始计算的
------------------------------
15

s1.rfind('v',-1,-20)    # 区间指定 -1 表示字符串的结尾,由于区间是从左边向右边的顺序,所以 -1,-20 这种指定区间的方法是非法的,找不到。
------------------------------
-1

in 操作

判断指定的元素是否在后面的可迭代对象中,有则返回 True ,否则返回 False

s1 = 'I am very very very sorry'

'v' in s1 
------------------------------
True

1 in range(5)
------------------------------
True

'1' in range(5)
------------------------------
False

len() 全局通用的内置函数

s1 = 'slfjslfs'
len([s1])
------------------------------
1

s1 = 'slfjslfs'
len(s1)
------------------------------
8

len([1])
------------------------------
1

len(())
------------------------------
0

len((1))
#---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-163-1efbf88b4bde> in <module>
----> 1 len((1))


TypeError: object of type 'int' has no len()

------------------------------


len((1,))   # 元组中单个元素要加逗号
------------------------------
1

len((1 + 2,))     # 元组中单个元素要加逗号
------------------------------
1

count() 字符串查找

S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
由于要遍历,所以时间复杂度是 O(n)
可以指定遍历的区间

s1 = 'saasaas'
s1.count('s')
------------------------------
3

s1 = 'saasaas'
s1.count('s',3)  # 这种指定的是 左边闭区间,有便是到末尾的闭区间
------------------------------
2

s1 = 'aaaa'
s1.count('a',2, 3)   # 这样指定的区间是 左闭区间,右开区间
------------------------------
1

s1 = 'aaaa'
s1.count('a',2, -1)  # 这样指定的区间是 左闭区间,右开区间, -1 指的是 尾
------------------------------
1

字符串判断 endswith() & startswith()

endswith() 返回bool,时间复杂度是 O(1),不会遍历全部元素,不怕超界

S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.

s1 = 'I am very very very sorry'
s1.endswith('I')
------------------------------
False

s1 = 'I am very very very sorry'
s1.endswith('sorry',0, -1)   # -1指的是末尾
------------------------------
False

s1 = 'I am very very very sorry'
s1.endswith('sorry',0, 10000)  # 不怕超界
------------------------------
True

startswith() 返回bool,时间复杂度是 O(1),不会遍历全部元素,不怕超界

S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.

s1 = 'I am very very very sorry'
s1.startswith('I')
------------------------------
True

s1 = 'I am very very very sorry'
s1.startswith('sorry',0, -1)   # -1指的是末尾
------------------------------
False

字符串的 'is' 系列的判断

isalpha() 判断是否“全部是”字符串

S.isalpha() -> bool
Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.

s1 = 'I am very very very sorry'  # 有空格,所以返回的是False  
s1.isalpha()   
------------------------------
False

s1 = 'I am very very very sorry'    # --> 'Iamveryveryverysorry'
s1.replace(' ','').isalpha()
------------------------------
True

s1 = 'abc123'
s1.isalpha()
------------------------------
False

isalnum() 判断是否全部是数字

S.isalnum() -> bool
Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.

s1 = 'abc123'
s1.isalnum()
------------------------------
True

s1 = 'abc123'
s1.isdigit()
------------------------------
False

s1 = '123'
s1.isdigit()
------------------------------
True

s1 = '1 23'
s1.isdigit()
------------------------------
False

isdecimal() 判断字符串中是否只有数字

S.isdecimal() -> bool
Return True if there are only decimal characters in S,False otherwise.

s1 = '123'
s1.isdecimal()
------------------------------
True

s1 = 'abc123'
s1.isdecimal()
------------------------------
False

s1 = '123.0'
s1.isdecimal()
------------------------------
False

s1 = '-123'
s1.isdecimal()
------------------------------
False

s1 = '1 23'
s1.isdecimal()
------------------------------
False

isspace() 判断字符串中是否只有空白字符串(至少有一个空白字符串,为空返回False)

S.isspace() -> bool
Return True if all characters in S are whitespace and there is at least one character in S, False otherwise.

s1 = ''
s1.isspace()
------------------------------
False

s1 = ' '
s1.isspace()
------------------------------
True

s1 = '     '
s1.isspace()
------------------------------
True

s1 = '\n'
s1.isspace()
------------------------------
True

s1 = '\t'
s1.isspace()
------------------------------
True

s1 = '\r\n\t'
s1.isspace()
------------------------------
True

s1 = '1 \t'
s1.isspace()
------------------------------
False

s1 = 'abc'
s1.isspace()
------------------------------
False

s1 = 'ab c'
s1.isspace()
------------------------------
False

isnumeric() 判断字符串是否值纯数字的

小数点返回为 False ,因为小数中有点 '.',点不是一个数字

'1'.isnumeric()
------------------------------
True

1.isnumeric() # 数值类型是没有 isnumeric 方法的
------------------------------
File "<ipython-input-80-64e5789b0206>", line 1
    1.isnumeric() # 数值类型是没有 isnumeric 方法的
                ^
SyntaxError: invalid syntax
    

'1.2'.isnumeric()
------------------------------
False

'-1'.isnumeric()
------------------------------
False

isidentifier() 判断是否是标识符(也就是合法的变量名)

'1'.isidentifier()  # 判断是否是 标识符,还是啊比较常用
------------------------------
False

'abc1'.isidentifier()
------------------------------
True

'abc1'.isidentifier()
------------------------------
True

'abc1_'.isidentifier()
------------------------------
True

'1abc_'.isidentifier()
------------------------------
False

'_1abc_'.isidentifier()
------------------------------
True

'xu@magedu.com'.isalnum()
------------------------------
False

几种数字的判断比较

print('1'.isalnum())
print('1'.isnumeric())
print('1'.isdigit())
print('1'.isdecimal())
print('-' * 20)
print('1.1'.isalnum(),  'a.1'.isalnum(),  'a1'.isalnum(),  '01'.isalnum())
print('0.1'.isnumeric(),'a.1'.isnumeric(),'1a'.isnumeric(),'01'.isnumeric())
print('0.1'.isdigit(),  'a.1'.isdigit(),  '1a'.isdigit(),  '01'.isdigit())
print('1.1'.isdecimal(),'a.1'.isdecimal(),'1a'.isdecimal(),'01'.isdecimal())
------------------------------------------------------------------------------
C:\python36\python.exe D:/pyporject/test/test01.py
True
True
True
True
--------------------
False False True True
False False False True
False False False True
False False False True

字符串的格式化

join()方法实现字符串拼接

参数是一个可迭代对象,并且元素只能是字符串类型

'+'.join(123)  #  参数需要是一个可迭代对象
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-39-71942d76f56e> in <module>
----> 1 '+'.join(123)  #


TypeError: can only join an iterable


lst = ['a','b','c']
'+'.join(lst)
------------------------------
'a+b+c'

''.join('a','b','c')   # 只能接受一个可迭代对象作为参数
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-41-798f2ab6da4a> in <module>
----> 1 ''.join('a','b','c')   # 只能接受一个可迭代对象作为参数


TypeError: join() takes exactly one argument (3 given)


'+'.join('a b c')
------------------------------
'a+ +b+ +c'

'+'.join('abc')
------------------------------
'a+b+c'

'+'.join(list(range(5)))  # 参数只能是字符串的可迭代对象
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

<ipython-input-47-dc8b3355f264> in <module>
----> 1 '+'.join(list(range(5)))  # 参数只能是字符串的可迭代对象


TypeError: sequence item 0: expected str instance, int found

'+'.join(str(list(range(5))))  # 参数只能是字符串的可迭代对象
------------------------------
'[+0+,+ +1+,+ +2+,+ +3+,+ +4+]'

+ 加号实现字符串的拼接

拼接字符串需要事先将不是字符串类型的数据转化为字符串类型

str(123) + 'abc'
------------------------------
'123abc'


123 + 'abc'
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-50-ab849117efab> in <module>
----> 1 123 + 'abc'


TypeError: unsupported operand type(s) for +: 'int' and 'str'

C 语言风格的 printf

格式要求:
占位符: 使用 % 和试试字符组成(%s %d 等等)%s是字符类型的占位符,%d是的数值类型的占位符
占位符中还可以插入修饰字符,例如 %03d 表示打印3个位置,不够的前面补 0
format % values, 格式字符串和被格式的值之间使用 % 分隔
values只能是一个对象,或是一个与格式字符串占位符数目相等的元组,或一个字典

"%d" % 1
------------------------------
'1'

"%d %s" % (1,2)
------------------------------
'1 2'

"%d %s" % ('1',2)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-100-f82b11953651> in <module>
----> 1 "%d %s" % ('1',2)


TypeError: %d format: a number is required, not str


"%s %s" % ('1',2)
------------------------------
'1 2'

"%s %30s" % (1,2)
------------------------------
'1                              2'

"%s %08d" % (1,2)
------------------------------
'1 00000002'

"%s %-08d" % (1,2)
------------------------------
'1 2       '

"%03d" % (1)  # 这样写不是一个元组,而是一个对象 1
------------------------------
'001'

"%03d" % (1,)
------------------------------
'001'

"%03d  %03d " % (1,2)
------------------------------
'001  002 '

'%03d%%' % 1   # %% 转义 %
------------------------------
'001%'

'%03f%%' % 1   # %% 转义 %
------------------------------
'1.000000%'

'0x%X' % 10   # %% 转义 %
------------------------------
'0xA'

'0x%x' % 10   # %% 转义 %
------------------------------
In [38]: '0x%x' % 10   # %% 转义 %                                                                                  
Out[38]: '0xa'

'%3.2f%%, 0x%x, 0X%02X' % (34.35324, 15, 10)  
# x 是十六进制的小写形式 X是大写的形式
# % 前面的 0x 和 0X 是添加的修饰字符
------------------------------
'34.35%, 0xf, 0X0A'

format() 函数实现字符串的格式化 ***

"{} {xxx}".format(*args, **kwargs) -> str
args 是可变位置参数,是一个元组
kwargs是可变关键字参数,是一个字典
花括号{} 表示占位符
{} 表示按照顺序匹配位置承参数,{n} 表示去取位置参数索引为 n 的值
{xxx} 表示在关键字参数中搜索名称一致的
{{}} 表示打印花括号

'{}'.format

"{}:{}".format("192.178.1.100",8888)
------------------------------
'192.178.1.100:8888'

"{server} {1}:{0}".format(8888,'192.168.0.101',server='www.xxx.com')
------------------------------
'www.xxx.com 192.168.0.101:8888'

"{0}{0}{0}".format(('www','magedu','com'))
------------------------------
"('www', 'magedu', 'com')('www', 'magedu', 'com')('www', 'magedu', 'com')"

"{0[0]}.{0[1]}.{0[2]}".format(('www','magedu','com'))
------------------------------
'www.magedu.com'

"{}.{}.{}".format('www','magedu','com')
------------------------------
'www.magedu.com'

通过namedtuple 演示如何实现对象属性访问与字符串format的配合

In [41]: from collections import namedtuple   
In [42]: Point = namedtuple('Point', 'x y')   
In [43]: p1 = Point(4, 5)                     
In [44]: p1                                   
Out[44]: Point(x=4, y=5)
In [45]: '{0.x} {0.y} {1}'.format(p1, 'abc')  
Out[45]: '4 5 abc'

format的对齐

"{0}*{1}={2:<5}".format(3, 4, 3 * 4)  # 左对齐
----------------------------
'3*4=12   '

"{0}*{1}={2:0<5}".format(3, 4, 3 * 4)  # 左对并填充 0
----------------------------
'3*4=12000'

"{0}*{1}={2:>5}".format(3, 4, 3 * 4)  # 右对并填充 0
----------------------------
'3*4=   12'

"{0}*{1}={2:5}".format(3, 4, 3 * 4)  # 默认就是右对并
----------------------------
'3*4=   12'

"{0}*{1}={2:0>5}".format(3, 4, 3 * 4)  # 右对齐
----------------------------
'3*4=00012'

"{0}*{1}={2:+>5}".format(3, 4, 3 * 4)  # 右对齐并指定其他的填充字符串
----------------------------
'3*4=+++12'

"{0}*{1}={2:^5}".format(3, 4, 3 * 4)  # 居中对齐
----------------------------
'3*4= 12  '

"{0}*{1}={2:@^6}".format(3, 4, 3 * 4)  
# 居中对齐并并指定填充是定的字符(只能指定一个填充字符)
----------------------------
'3*4=@@12@@'

"{}*{}={:@^6}".format(3, 4, 3 * 4)  
----------------------------
'3*4=@@12@@'

"{0}**{1}={2:^5}".format(10000, 4, 10000 ** 4)  
# 居中对齐,如果返回的结果宽度大于指定的 5 , 就会使用实际的宽度,
# 因为指定的宽度是不够实现居中打印的
----------------------------
'10000**4=10000000000000000'

通过format() 实现进制的转换

"int:{0:d}; hex:{0:x}; oct:{0:o}; bin:{0:b}".format(42)
# int:{0:d} 中的 0 指的是format()中的索引,
# int:{0:d} 中的 d 指的是转换为十进制,
# int:{0:x} 中的 x 指的是转换为十六进制,
# int:{0:o} 中的 o 指的是转换为八进制,
# int:{0:b} 中的 b 指的是转换为二进制,
# 其余的都是添加的修饰符
----------------------------
'int:42; hex:2a; oct:52; bin:101010'

"int:{0:d}; hex:{1:x}; oct:{0:o}; bin:{1:b}".format(42, 61)
----------------------------
'int:42; hex:3d; oct:52; bin:111101'

"int:{0:#d}; hex:{1:#x}; oct:{0:#o}; bin:{1:#b}".format(42, 61)
# {1:#x} 中的井号 "#" 表示自动添加 进制的标识符 十六进制 0x,八进制 0o, 二进制 0b, 十进制省略不写
----------------------------
'int:42; hex:0x3d; oct:0o52; bin:0b111101'

通过format() 实现浮点数的格式化

print("{}".format(3 ** 0.5))  
# 默认是的输出
----------------------------
1.7320508075688772

print("{:f}".format(3 ** 0.5))  
# 使用 f 指定为浮点数(浮点默认的精度是6位)
----------------------------
1.732051

print("{:20f}".format(3 ** 0.5))  # 右对齐宽度为20
print("{:>20f}".format(3 ** 0.5))   # 右对齐宽度为20
print("{:<20f}".format(3 ** 0.5))   # 左对齐宽度为20
----------------------------
1.732051
1.732051
1.732051            
    
print("{:2}".format(101.102))
# 如果返回的结果宽度大于指定的 2 , 就会使用实际的宽度,
----------------------------
101.102

print("{:.4}".format(3 ** 0.5))  
# 结果保留 4 位数(包括整数部分和小数部分)
----------------------------
1.732

print("{:.4f}".format(3 ** 0.5))  
print("{:<.4f}".format(3 ** 0.5))  
# 小数点后保留 4 位小数
----------------------------
1.7321
1.7321

print("{:5.2}".format(3 ** 0.5)) # 结果宽度为5 保留 2 位数
print("{:>5.2}".format(3 ** 0.5))  # 结果宽度为5 保留 2 位数
print("{:<5.2}".format(3 ** 0.5))  # 结果宽度为5 保留 2 位数 
print("{:5.3}".format(3 ** 0.5))  # 结果宽度为5 保留 3 位数
print("{:1.2}".format(3 ** 0.5)) # 结果宽度为1 保留 2 位数
----------------------------
1.7
1.7
1.7  
1.73
1.7

print("{:5.2f}".format(3 ** 0.5))  # 结果宽度为5 小数点后保留 2 位小数
print("{:>5.2f}".format(3 ** 0.5))  # 结果宽度为5 小数点后保留 2 位小数
print("{:<5.2f}".format(3 ** 0.5))   # 结果宽度为5 小数点后保留 2 位小数
print("{:5.3f}".format(3 ** 0.5))  # 结果宽度为5 小数点后保留 2 位小数
print("{:1.2f}".format(3 ** 0.5)) # 结果宽度为1小数点后保留 2 位小数
----------------------------
1.73
1.73
1.73 
1.732
1.73

print("{:3.3%}".format(3 ** 0.5))  # 使用百分比形式显示
----------------------------
173.205%

通过format() 将十进制的地址转换为十六进制的地址

使用到的知识点是 "参数的解构"

octets = [192,168,0,1]
"{:02X}:{:02X}:{:02X}:{:02X}".format(*octets)
----------------------------
'C0:A8:00:01'

octets1 = '192.168.0.1'.split(".")
octets2 = map(int,octets1)  
print(octets1)
print(octets2)
# 在map()函数中,使用 int 函数将可迭代对象octets1中的元素做转换,返回的是一个新的对象,用来在后面的format中进行参数解构
"{:02X}:{:02X}:{:02X}:{:02X}".format(*octets2)

----------------------------

In [46]: octets1 = '192.168.0.1'.split(".")              
In [47]: octets2 = map(int,octets1)                      
In [48]: print(octets1)                                  
['192', '168', '0', '1']

In [49]: print(octets2)                                  
<map object at 0x7fbbf6408f98>

In [50]: "{:02X}:{:02X}:{:02X}:{:02X}".format(*octets2)  
Out[50]: 'C0:A8:00:01'

本文链接:https://www.cnblogs.com/shichangming/p/10383878.html

posted @ 2018-03-03 15:25  scm1911  阅读(206)  评论(0编辑  收藏  举报
/** ####################################################################### */