輸入和輸出
今天只介紹 print()函數(shù)
輸出:print()打印出來的(控制臺)
print("helloworld")
my_str1 = "hello"
my_str2 = "world"
輸出多個變量的時候,中間會有分隔符(默認是空格)
修改輸出的分隔符
print(my_str1,my_str2,sep="&")
print函數(shù)默認輸出之后會換行
print("1",end="zhangsan")
print("2",end="\n\n")
print("3")
格式化輸出
整數(shù)的輸出
語法說明
格式化符號格式說明備注
%o 八進制 oct
%d 十進制 dec
%x 十六進制 hex壶硅。
舉個栗子
print('%o' % 20) # 八進制24
print('%d' % 20) # 十進制20
print('%x' % 24) # 十六進制18
浮點數(shù)輸出
語法說明
格式化符號說明備注
%f 保留小數(shù)點后面六位有效數(shù)字 float
%e 保留小數(shù)點后面六位有效數(shù)字
%g 在保證六位有效數(shù)字的前提下钳幅,使用小數(shù)方式赵誓,否則使用科學計數(shù)法涧卵。
舉個栗子:
print('%f' % 1.11) # 默認保留6位小數(shù)1.110000
print('%.1f' % 1.11) # 取1位小數(shù)1.1
print('%e' % 1.11) # 默認6位小數(shù)芹务,用科學計數(shù)法1.110000e+00
print('%.3e' % 1.11) # 取3位小數(shù)择份,用科學計數(shù)法1.110e+00
print('%g' % 1111.1111) # 默認6位有效數(shù)字1111.11
print('%.7g' % 1111.1111) # 取7位有效數(shù)字1111.111
print('%.2g' % 1111.1111) # 取2位有效數(shù)字狸吞,自動轉(zhuǎn)換為科學計數(shù)法1.1e+03
字符串輸出
語法說明
格式化符號說明備注
%s 字符串輸出 string
%10s 右對齊胆描,占位符 10位
%-10s 左對齊炬灭,占位符 10 位
%.2s 截取 2 位字符串
%10.2s10 位占位符醋粟,截取兩位字符串。
舉個栗子:
print('%s' % 'hello world') # 字符串輸出hello world
print('%20s' % 'hello world') # 右對齊重归,取20位米愿,不夠則補位 hello world
print('%-20s' % 'hello world') # 左對齊,取20位鼻吮,不夠則補位hello world
print('%.2s' % 'hello world') # 取2位he
print('%10.2s' % 'hello world') # 右對齊育苟,取2位 he
print('%-10.2s' % 'hello world') # 左對齊,取2位he
輸入:獲取用戶鍵盤輸入的文字
input() 默認輸入的為 str 格式椎木,若用數(shù)學計算违柏,則需要轉(zhuǎn)換格式博烂,例:
a=input('請輸入數(shù)字:')
print(a*2)
假設(shè)輸入數(shù)值為3,則上例中得出結(jié)果為:
33
若將代碼修改為:
a=int(input('請輸入數(shù)字:'))
print(a*2)
則結(jié)果為:
6