開始學習Python第一天_字串的拼接+輸入字串
阿新 • • 發佈:2018-12-15
在日常的程式開發中,經常會使用到字串拼接的問題,比如過要輸出登陸者的使用者名稱,我就可以拿到使用者名稱和自己準備好的的字串進行拼接用來輸出 比如:早上好:登陸者的使用者名稱。這樣功能我在日常的開發還是很有用的,來現在介紹下字串拼接的集中方式:
數字拼接 | str = "Hello,{0}".format("Carr") |
%號拼接 | str = "Hello,%s" % ("Carr") |
{xxx}拼接 | str = "Hello,{_name}" .format("Carr") |
+號拼接 | str = "Hello," + "Carr" |
因為在拼接字串的時候名稱是自己輸入的,這裡我先說下輸入字串的程式碼:
_name_ = input("Input your UserName:")
程式碼解釋: _name_是接收輸入的變數,input輸入函式,“”中的字串是提示輸入的字串
字串拼接,我這裡準備的程式碼是多行字串的演示:
演示需要接受的字串:
_name_ = input("Input your UserName:") #輸入使用者名稱 _pas_ = input("Input your Password:") #輸入密碼 _age_ = input("Input your Age:") #輸入年齡 _address_ = input("Input your Address:")#輸入地址
第一種字串拼接方式(通過數字的方式拼接):
#第一種字串拼接方式
info_one = '''
----------- Your Info:{0} -----------
Name:{0}
PassWord:{1}
Age:{2}
Address:{3}
'''.format(_name_,_pas_,_age_,_address_)
print(info_one)
這裡的‘’‘’‘’不但可以作為註釋多行程式碼,還可以用來包裹多行字串 ,print是用來輸出字串
第二種字串拼接方式(%號拼接):
#第二種字串拼接方式種 info_two = ''' ----------- Your Info:%s ----------- Name:%s PassWord:%s Age:%s Address:%s ''' % (_name_,_name_,_pas_,_age_,_address_) print(info_two)
第三種字串拼接方式({xxx}拼接):
#第三種拼接方式
info_san = '''
----------- Your Info:{_name} -----------
Name:{_name}
PassWord:{_pass}
Age:{_age}
Address:{_add}
'''.format(_name=_name_,
_pass=_pas_,
_age=_age_,
_add=_address_)
print(info_san)
第四種字串拼接方式(+號拼接):
#第四種拼接方式
info_si = '''
----------- Your Info:''' + _name_ +''' -----------
Name:'''+_name_+''''
PassWord:'''+_pas_+'''
Age:'''+_age_+'''
Address:'''+_address_+'''
'''
print(info_si)
拼接字串的方法有很多種,我只舉了幾個例子,個人感覺 %和.format的方式比較方便些
效果展示:
Input your UserName:Carr
Input your Password:123456
Input your Age:22
Input your Address:山東省
============= 第一種拼接 =============
----------- Your Info:Carr -----------
Name:Carr
PassWord:123456
Age:22
Address:山東省
============= 第二種拼接 =============
----------- Your Info:Carr -----------
Name:Carr
PassWord:123456
Age:22
Address:山東省
============= 第三種拼接 =============
----------- Your Info:Carr -----------
Name:Carr
PassWord:123456
Age:22
Address:山東省
============= 第四種拼接 =============
----------- Your Info:Carr -----------
Name:Carr'
PassWord:123456
Age:22
Address:山東省