輸入input:
name=input('請輸入姓名:')
num=input('請輸入學号:')
print(name)
print(num)
print(type(name),type(num))
執行結果:
可以看出python預設的輸入資料類型是str型,即字元串型資料,想要讓輸入的num為整形,可以轉換資料類型:
num=int(input('請輸入學号:'))
*注意*python的預設輸入資料類型是str,需要輸入其他資料類型時需要進行轉換
輸出print:
name=python
num=
print('*******implementation results*******') #輸出一段字元串用''或""将字元串框起來
print(name) #輸出變量的值
print('*','name:',name,'\n','*','num:',num) #字元串和變量一起輸出,多個輸出項用','隔開,\n表示換行
print('*','name:',name,r'\n','\\n','*','num:',num) #如果不想讓\n換行,可以在' '之前加上r轉義,或者\\雙斜杠轉義,也适用于其他特殊字元的轉義
執行結果:
*******implementation results*******
python
* name: python
* num: 2018
* name: python \n \n * num: 2018
格式化輸出:
方法一:
name=input('請輸入姓名:')
num=int(input('請輸入學号:'))
interest=input('請輸入您的興趣愛好:')
age=int(input('請輸入您的年齡:'))
info = ''' #定義一個變量info
***********implementation results of info**************
Name:%s #占位符,輸出必須為str型資料
Num:%d #輸出必須為int型資料
Interest:%s
Age:%d
''' % (name,num,interest,age) #必須按照順序将變量名寫進來,第一個%s對應的是name,第二個%d對應的是num,以此類推
print(info) #輸出info
執行結果
***********implementation results of info**************
Name:byfoxx
Num:2018
Interest:gaming
Age:25
方法二(推薦方法):
name=input('請輸入姓名:')
num=int(input('請輸入學号:'))
interest=input('請輸入您的興趣愛好:')
age=int(input('請輸入您的年齡:'))
info2='''
***********implementation results of info2**************
Name:{_name} #相當于在{}内填入一個變量,該變量未指派
Num:{_num}
Interest:{_interest}
Age:{_age}
''' .format(_name=name,_num=num,_interest=interest,_age=age)#将info2外面的變量的值賦給我們剛剛填入的幾個變量,無需注意順序
print(info2) #輸出info2
執行結果:
***********implementation results of info2**************
Name:byfoxx
Num:2018
Interest:gaming
Age:25
方法三:
name=input('請輸入姓名:')
num=int(input('請輸入學号:'))
interest=input('請輸入您的興趣愛好:')
age=int(input('請輸入您的年齡:'))
info3='''
***********implementation results of info3**************
Name:{0}
Num:{1}
Interest:{2}
Age:{3}
'''.format(name,num,interest,age) #按從0到3的順序将要列印的變量寫在這裡
print(info3)
執行結果:
***********implementation results of info3**************
Name:byfoxx
Num:2018
Interest:gaming
Age:25
字元串拼接
+拼接
name=input('請輸入姓名:')
num=int(input('請輸入學号:'))
interest=input('請輸入您的興趣愛好:')
age=int(input('請輸入您的年齡:'))
info4='''
***********implementation results of info3**************
Name:'''+ name +'''
Interest:'''+interest+'''
'''
print(info4)
需要開辟多個記憶體區域出來,當連結字元串較多時效率較低。不推薦使用。
jion函數拼接
a = ['我們', '是', '祖國','的','花朵']
b =['we','are','flowers','of','fatherland']
flower_chn= ''.join(a) # ''中為分隔符,可以為空,可以為空格或其他字元
flower_eng=' '.join(b) #将清單b中的字元串連接配接起來指派給flower_eng,分隔符為空格
print(flower_chn,'\n',flower_eng)
執行結果:
我們是祖國的花朵
we are flowers of fatherland
jion對清單内字元串拼接來說非常友善,對多個字元串拼接是隻申請一次記憶體,效率也較高
字元串格式化
breakfast = '%s %s %d %s' % ('I', 'eat', ,'apples') #連接配接符寫在第一個''中即可,我寫了個空格,注意不同資料類型(整形要用%d)
print(breakfast)
執行結果
I eat apples
使用起來非常簡單友善,是一種常用方法