这一篇主要记录下 Python 的字符串输出形式,来自 Cescfangs 的个人博客。
str与repr很多时候用 Python 进行输出,我们会把其他类型的值转化成string进行输出(私以为是Python注重和人的交互,而string是最适合与人类进行交互的数据类型),有str()和repr()两种方法对数据类型进行转化,str()转化后的结果更适合与人进行交互,而repr()转化后的结果则可以被Python的解释器阅读,但当要转化的对象没有适合与人交互的类型时,str()转化的结果和repr()是一样的:
>>> s=\'hello world\'
>>> str(s)
\'hello world\'
>>> repr(s)
\"\'hello world\'\"
>>>
当交互的对象是人时,\’hello world\’显而易见就是一个字符串,字符串代表的意思是不言而喻,或者说人更关注\’ \’内的信息,而非\’ \’本身,但是机器则不同,如果直接把hello world传给机器,他很难处理这个数据,但是有了\’ \’后,Python的解释器就知道这是一个字符串,或者也可以这么说,相较于字符串的具体内容,机器更关心的是\’hello world\’这个整体,所以为了保存所需要的信息,repr()会给转化的对象加上\” \”。
>>> x=10
>>> s=\'the value of x is \'+repr(x)
>>> s
\'the value of x is 10\'
>>> u=\'the value of x is \'+str(x)
>>> u
\'the value of x is 10\'
>>>
对于这种组合类型的变量,str()和repr()的结果是一样的。
>>> h=\'hello \\n\'
>>> print(str(h))
hello
>>> print(repr(h))
\'hello \\n\'
>>>
str()和repr()的区别可见一斑。
>>> for x in range(11):
print(str(x).rjust(2), str(x * x).rjust(3), str(x**3).rjust(4))
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
str.rjust()方法不会对该变量做任何处理。只是返回一个新的变量,字符的长度根据所给的参数确定,对齐方式为右对齐,多余的空间用空格补齐,类似的还有str.ljust(),str.center()等。当所给的长度小于字符串本身的长度时,这些方法不会截止数据,而是原封不动返回,这可能会破坏美观,但是总比数据破坏要好吧?如果要强制截断数据,可以用str().ljust(n)[:n]这种形式:
>>> for x in range(11):
print(str(x).rjust(2), str(x * x).rjust(3), str(x**3).rjust(3)[:3])
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 100
还有一种str.zfill()方法,与str.rjust()不同,它补齐的是0而不是空格,而且它能够理解正负号的意思:
>>> \'123\'.zfill(7)
\'0000123\'
>>> \'-12.3\'.zfill(7)
\'-0012.3\'
>>> \'123456\'.zfill(4)
\'123456\'
>>>
这是一种和C语言非常相似的输出方法,但是个人觉得更加好用:
>>> print(\'{} is a {}\'.format(\'Cescfangs\', \'gooner\'))
Cescfangs is a gooner
\'{}\’的内容会被format()中的参数所替代,可以在\'{}\’里填上数字来指定format()中的位置,但是如果\'{}\’里的是参数,其中的内容会以被format()中的字符替换:
>>> print(\'{1} is a {0}\'.format(\'Cescfangs\', \'gooner\'))
gooner is a Cescfangs
>>> print(\'{Ramsey} is a {gunner}\'.format(Ramsey=\'Cescfangs\', gunner=\'gooner\'))
Cescfangs is a gooner
还可以用\’:\’对输出的范围进行控制,我们输出小数点后三位的$\\pi$:
>>> print(\'value of pi is {0:.3f}\'.format(math.pi))
value of pi is 3.142
\’:\’可以起到固定位数输出的作用,这会让我们的输出更加漂亮:
>>> arsenal = {\'Ramsey\': 16, \'Rosciky\': 7, \'Chambers\': 21, \'Ozil\': 11}
>>> for player, number in arsenal.items():
print(\'{0:10}--->{1:3d}\'.format(player, number))
Rosciky ---> 7
Ozil ---> 11
Ramsey ---> 16
Chambers ---> 21
未完待续
下一篇:爬取美少女图片