
Happiness is to find someone who can give you warm and share your life together.
幸福,就是找一個溫暖的人過一輩子。
讀取鍵盤輸入
input()函數(shù)從標(biāo)準(zhǔn)輸入讀入一行文本,默認(rèn)的標(biāo)準(zhǔn)輸入是鍵盤
示例:
str = input("請輸入:");
print ("你輸入的內(nèi)容是: ", str)
打印結(jié)果:
請輸入:mazy
你輸入的內(nèi)容是: mazy
輸出
print()函數(shù)主要負(fù)責(zé) Python 的輸出
-
str(): 函數(shù)返回一個用戶易讀的表達(dá)形式 -
repr(): 產(chǎn)生一個解釋器易讀的表達(dá)形式,可以轉(zhuǎn)義字符串中的特殊字符
示例:
s = "Hello, Mazy"
print(s)
print(str(s))
print(repr(s))
print("------")
# repr() 函數(shù)可以轉(zhuǎn)義字符串中的特殊字符
s1 = "Hello, Mazy\n"
print(repr(s1))
輸出結(jié)果
Hello, Mazy # 直接輸出
Hello, Mazy # str() 輸出
'Hello, Mazy' # repr() 輸出
------
'Hello, Mazy\n' # repr() 輸出
常見格式化函數(shù):
- ljust(): 它可以將字符串靠右, 并在左邊填充
- rjust(): 它可以將字符串靠右, 并在左邊填充
- center(): 它可以將字符串居中, 并在左右邊填充
- zfill(): 它會在數(shù)字或字符的左邊填充 0
示例:
print(s.ljust(50,"-"))
print(s.rjust(50,"-"))
print(s.center(50,"-"))
print("12".zfill(50))
輸出結(jié)果:
Hello, Mazy---------------------------------------
---------------------------------------Hello, Mazy
-------------------Hello, Mazy--------------------
00000000000000000000000000000000000000000000000012
str.format() 的基本使用
格式:"{}...{}...".format( parameter1, parameter2,... )
1、括號及其里面的字符 (稱作格式化字段) 將會被 format() 中的參數(shù)替換
示例1:
print('{} 網(wǎng)址: "{}"'.format("Mazy's home", 'http://imazy.cn'))
結(jié)果:
Mazy's home 網(wǎng)址: "http://imazy.cn"
2、在括號中的數(shù)字用于指向傳入對象在 format() 中的位置
示例2:
print('{0} like {1}'.format("Eric", 'Joy'))
print('{1} like {0}'.format("Eric", 'Joy'))
結(jié)果:
Eric like Joy
Joy like Eric
3、如果在 format() 中使用了關(guān)鍵字參數(shù), 那么它們的值會指向使用該名字的參數(shù)
使用關(guān)鍵字參數(shù)無視參數(shù)順序
示例3:
print('{name} 網(wǎng)址: "{site}"'.format(name="Mazy's home", site='http://imazy.cn'))
# 更換參數(shù)位置
print('{name} 網(wǎng)址: "{site}"'.format(site='http://imazy.cn', name="Mazy's home"))
結(jié)果:
Mazy's home 網(wǎng)址: "http://imazy.cn"
Mazy's home 網(wǎng)址: "http://imazy.cn"
4、位置及關(guān)鍵字參數(shù)可以任意的結(jié)合
注意,關(guān)鍵字參數(shù)必須放最后
示例4:
print('{0} like {1} and {other}'.format("Eric", 'Joy', other="Vivan"))
# err: SyntaxError: positional argument follows keyword argument
# print('{0} like {1} and {other}'.format( other="Vivan", "Eric", 'Joy'))
結(jié)果:
Eric like Joy and Vivan
5、可選項(xiàng) : 和格式標(biāo)識符可以跟著字段名,這就允許對值進(jìn)行更好的格式化
示例5:
import math
print('常量 PI 的值近似為 {0:.3f}。'.format(math.pi))
結(jié)果:
常量 PI 的值近似為 3.142
6、舊式字符串格式化
%操作符也可以實(shí)現(xiàn)字符串格式化
import math
# 一個參數(shù)
print('常量 PI 的值近似為:%5.3f' % math.pi)
# 多個參數(shù)
print('常量 %s 的值近似為:%.3f' % ("PI", math.pi))
輸出結(jié)果:
常量 PI 的值近似為:3.142
常量 PI 的值近似為:3.142