1. 程式人生 > 其它 >python(二)基礎語法-input與print的用法

python(二)基礎語法-input與print的用法

技術標籤:Pythonpython

§ python-input與print的用法


使用軟體為Windows下的vscode。

一.input()函式

1.函式說明

  • 函式在庫中的原型及解釋說明如下
def input(prompt: Any=...)
'''
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. On *nix systems, readline is used if available.
'''
  • 函式接受一個標準輸入資料,返回為 string 型別。
  • 函式的引數可選,如果填寫,則在接收字串的時候會列印提示。
  • 回車標誌著輸入結束,但是回車不會被輸入到接收資料的變數中
  • 函式使用格式
data = input()  # 從鍵盤獲取字元,以回車結束

2.函式使用

2.1 資料輸入

data = input()  # 輸入資料
print(data)     # 列印輸入的資料
print(type(data))  # 列印輸入的資料型別
print(len(data))   # 列印輸入字串的長度

2.2 帶提示的資料輸入

data = input("Please enter your data:"
) # 輸入資料 print(data) # 列印輸入的資料 print(type(data)) # 列印輸入的資料型別 print(len(data)) # 列印輸入字串的長度

二.print()函式

1.函式說明

  • 函式在庫中的原型及解釋說明如下
def print(*values: object, sep: Optional[Text]=..., end: Optional[Text]=..., file: Optional[_Writer]=..., flush: bool=...)
'''
Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: 
file: a file-like object (stream); defaults to the current sys.stdout. 
sep: string inserted between values, default a space. 
end: string appended after the last value, default a newline. 
flush: whether to forcibly flush the stream.
'''

2.函式使用

2.1 多種變數型別輸出

data1 = "hello word!"    # 字串型別資料
print(data1)
data2 = 999              # 整型資料
print(data2)
data3 = 3.14             # 浮點型資料
print(data3)
data4 = (1, 2, 3)        # 元組資料
print(data4)
data5 = ["a", "b", "c"]  # 列表型別資料
print(data5)
data6 = {"key1": 123, "key2": "abc"}  # 字典型別資料
print(data6)

2.2 格式化輸出

  • 格式化輸出格式
格式符號轉換
%c格式化字元及其ASCII碼
%s通過str() 字串轉換來格式化
%i有符號十進位制整數
%d有符號十進位制整數
%u無符號十進位制整數
%o無符號八進位制整數
%x無符號十六進位制整數(小寫字母)
%X無符號十六進位制整數(大寫字母)
%e用科學計數法格式化浮點數
%E作用同%e,用科學計數法格式化浮點數
%f浮點數字,可指定小數點後的精度
%g%f和%e 的簡寫
%G%f和%E的簡寫
%p用十六進位制數格式化變數的地址
  • 輔助功能
格式符號功能
*寬度或者小數點精度
-左對齊
+在正數前面顯示加號( + )
#在八進位制數前面顯示零(‘0’),在十六進位制前面顯示’0x’或者’0X’(取決於用的是’x’還是’X’)
0顯示的數字前面填充’0’而不是預設的空格
  • 輸出例項1
# 列印字串長度
print("The length of [%s] is %d bytes" % ("hello world!", len("hello world!")))
  • 輸出例項2
pi = 3.141592653
print("pi = %-10.4f" % (pi))  # 寬10位元組,精度3位小數,左對齊
print("pi = %+10.4f" % (pi))  # 寬10位元組,精度3位小數,預設右對齊,顯示"±"號
print("pi = %08.4f" % (pi))   # 寬10位元組,精度3位小數
print("pi = %.*f" % (3, pi))  # 用*從後面的元組中讀取欄位寬度或精度

2.3 format格式化輸出

  format把字串當成一個模板,通過傳入的引數進行格式化,並且使用大括號"{}“作為特殊字元代替”%",功能相對於%格式化輸出更為強大。

  • 函式原型如下
def format(*args: object, **kwargs: object)
'''
Return value.format(format_spec)
format_spec defaults to the empty string. 
See the Format Specification Mini-Language section of help('FORMATTING') for details.
'''
  • 2.3.1 基本輸出方式
print("{} {}".format("hello", "world"))    # 不帶任何引數
print("{0} {1}".format("hello", "world"))  # 帶數字編號,數字編號指定順序

print("{0} {1} {0}".format("hello", "world"))  # 打亂順序
print("{2} {1} {0}".format("hello", "world", "hk"))

print("{a} {b} {a}".format(b="hello", a="world"))  # 帶關鍵字指定相應的字串
  • 2.3.1 對齊與小數取位數操作
符號功能
<(預設)左對齊
>右對齊
^中間對齊
{:4s}輸出佔4個位元組
{:.2f}輸出兩位小數
print("{} && {}".format("hello", "world"))  # 預設左對齊

print("{:15s} && {:>15s}".format("hello", "world"))  # 15位元組輸出,第一個預設左對齊,第二個右對齊
# 注意這裡要想在前邊加補齊符號,不能省略預設的左對齊符號
print("{:=<15s} && {:=>15s}".format("hello", "world"))  # 15位元組輸出,第一個預設左對齊,第二個右對齊,不足的用=補齊
print("{:=^10s} && {:=^10s}".format("hello", "world"))  # 10位元組中間對齊輸出,不足的位元組補=

print("{} is {:.3f}".format(3.1415926, 3.1415926))  # 保留2位小數
print("{0} is {0:>10.3f}".format(3.1415926))  # 保留3位小數,10位元組右對齊輸出
  • 2.3.2 格式化輸出
格式符號功能
d十進位制整數輸出
b二進位制輸出
x十六進位制輸出,9-15以用小寫字母a-f
o八進位制輸出
c字元,整數的話會轉化為ASCII碼
s字串輸出
e冪符號,用科學計數法列印數字
g一般格式,將數值以fixed-point number輸出,數值很大的時候,用冪形式列印
n數字,當值為整數時和’d’相同,值為浮點數時和’g’相同,不同的是它會根據區域設定插入數字分隔符
%百分數,將數值乘以100然後以fixed-point number(‘f’)格式列印,會在後邊加上%
print("d:{:d}".format(33))  # 十進位制整數輸出
print("b:{:b}".format(33))  # 二進位制輸出
print("x:{:x}".format(33))  # 十六進位制輸出,9-15以用小寫字母a-f
print("o:{:o}".format(33))  # 八進位制輸出
print("c:{:c}".format(33))  # 字元,整數的話會轉化為ASCII碼
print("s:{:s}".format("hello"))  # 字串輸出
print("e:{:.13e}".format(33))  # 冪符號,用科學計數法列印數字
print("g:{:g}".format(33))  # 一般格式,將數值以fixed-point number輸出,數值很大的時候,用冪形式列印
print("n:{:n}".format(33))  # 數字,當值為整數時和'd'相同,值為浮點數時和'g'相同,不同的是它會根據區域設定插入數字分隔符
print("%:{:.3%}".format(33))  # 百分數輸出,保留三位小數
  • 2.3.3 漢字與字母輸出對齊以及format引數巢狀

  在漢字與字母輸出的過程中,漢字在utf8編碼中被視為3個位元組,在GBK編碼中是2個位元組,在uicode編碼中是1個位元組。

print(len("位元組數"))                 # 預設編碼格式下漢字長度
print(len("位元組數".encode("utf8")))  # utf8下漢字長度
print(len("位元組數".encode("GBK")))   # GBK下漢字長度

  在控制檯進行漢字顯示的時候,程式將其當作一個位元組處理,但是顯示的時候卻是佔用了兩個位元組的位置,這就導致了漢字與字母不能對齊的問題。如下例,打印表頭及一些資訊的時候,字母與漢字夾雜在一起,以同樣的位元組數列印,但是所佔長度卻不同。

Infos = [
        {"ID": "101", "name": "唐昊", "sex": "男", "age": "55", "phonenum": "11111111111"},  # 0
        {"ID": "102", "name": "Ayin", "sex": "女", "age": "50", "phonenum": "22222222222"},  # 1
        {"ID": "103", "name": "唐三", "sex": "男", "age": "20", "phonenum": "33333333333"},  # 2
        {"ID": "104", "name": "XiaoWu", "sex": "女", "age": "16", "phonenum": "55555555555"},  # 3
        ]
TableHeader = ["序號", "姓名", "性別", "年齡", "手機號"]

print("|{0:^{len0}s}|{1:^{len1}s}|{2:^{len2}s}|{3:^{len3}s}|{4:^{len4}s}|".format(
      TableHeader[0], TableHeader[1], TableHeader[2], TableHeader[3], TableHeader[4],
      len0=15, len1=15, len2=15, len3=15, len4=15))
for temp in Infos:
    print("|{0:^{len0}s}|{1:^{len1}s}|{2:^{len2}s}|{3:^{len3}s}|{4:^{len4}s}|".format(
            temp["ID"], temp["name"], temp["sex"], temp["age"], temp["phonenum"],
            len0=15, len1=15, len2=15, len3=15, len4=15))

  解決方法:len = 固定長度 - len(“中文內容”.encode(“GBK”)) + len(“中文內容”)

  比如“位元組數”三個字,預設的位元組長度為3,但是卻要佔用6個位元組的位置,所以總的輸出長度要減去這三個位置,才可以與其他的同長度的字串對齊,所以就得到了上述的式子。
  所以修改程式如下

print("|{0:^{len0}s}|{1:^{len1}s}|{2:^{len2}s}|{3:^{len3}s}|{4:^{len4}s}|".format(
      TableHeader[0], TableHeader[1], TableHeader[2], TableHeader[3], TableHeader[4],
      len0=15 - len(TableHeader[0].encode("GBK")) + len(TableHeader[0]),
      len1=15 - len(TableHeader[1].encode("GBK")) + len(TableHeader[1]),
      len2=15 - len(TableHeader[2].encode("GBK")) + len(TableHeader[2]),
      len3=15 - len(TableHeader[3].encode("GBK")) + len(TableHeader[3]),
      len4=15 - len(TableHeader[4].encode("GBK")) + len(TableHeader[4])))
for temp in Infos:
    print("|{0:^{len0}s}|{1:^{len1}s}|{2:^{len2}s}|{3:^{len3}s}|{4:^{len4}s}|".format(
            temp["ID"], temp["name"], temp["sex"], temp["age"], temp["phonenum"],
            len0=15 - len(temp["ID"].encode("GBK")) + len(temp["ID"]),
            len1=15 - len(temp["name"].encode("GBK")) + len(temp["name"]),
            len2=15 - len(temp["sex"].encode("GBK")) + len(temp["sex"]),
            len3=15 - len(temp["age"].encode("GBK")) + len(temp["age"]),
            len4=15 - len(temp["phonenum"].encode("GBK")) + len(temp["phonenum"])))

2.4 不換行輸出

  在python中的print函式在列印內容的時候會自動增加換行符號,但是print函式中有一個可選引數,就是end,使用end可以指定print結尾字元

  • 使用格式如下
print("hello world!", end="char")  # char為指定的結尾字元
  • 例項
print("hello world! 1")  # 不指定結尾字元,預設換行輸出
print("hello world! 2")

print("hello world! 3", end="")  # 指定結尾字元為空格
print("hello world! 4")

print("hello world! 5", end="\t")  # 指定結尾字元為一個製表符
print("hello world! 6")

print("hello world! 7", end="|")  # 指定結尾字元為  |
print("hello world! 8")

三.轉義字元

轉義意義
\在行尾的續行符,即一行未完,轉到下一行繼續寫
\\反斜槓(保留 \)
\’反斜槓(保留 ')
\"反斜槓(保留 ")
\b退格(Backspace)
\f換頁
\n換行符
\r回車符
\t水平製表符
\xhh十六進位制數,hh 代表字元,如 \x0a 代表換行