Python中字符串拼接的三種方式


在Python中,我們經常會遇到字符串的拼接問題,在這里我總結了三種字符串的拼接方式:

    1.使用加號(+)號進行拼接

    加號(+)號拼接是我第一次學習Python常用的方法,我們只需要把我們要加的拼接到一起就行了,不是變量的使用單引號或雙引號括起來,是變量直接相加就可以,但是我們一定要注意的是,當有數字的時候一定要轉化為字符串格式才能夠相加,不然會報錯。

name = input("Please input your name: ")
age = input("Please input your age: ")
sex = input("Please input your sex: ")

print("Information of " + name + ":" + "\n\tName:" + name + "\n\tAge:" + age + "\n\tSex:" + sex)

輸出結果如下:

Information of Alex:
    Name:Alex
    Age:38
    Sex:girl

    字符串拼接直接進行相加就可以,比較容易理解,但是一定要記得,變量直接相加,不是變量就要用引號引起來,不然會出錯,另外數字是要轉換為字符串才能夠進行相加的,這點一定要記住,不能把數字直接相加。

    2.使用%進行拼接

name = input("Please input your name: ")
age = input("Please input your age: ")
sex = input("Please input your sex: ")

print("Information of \n\tName:%s\n\tAge:%s\n\tSex:%s" %(name,age,sex))

輸出結果如下:

Information of Alex:
    Name:Alex
    Age:38
    Sex:girl

    第二種方式是使用%號的方法,我們在后面把變量統一進行添加,這樣避免了使用加號的情況,能夠讓代碼更加簡短,這種方式我也喜歡,簡單方便,只要知道自己需要的是什么樣的信息,在里面設置格式,然后把變量進行添加就可以了。

    3.使用單引號('''''')或者雙引號("""""")的方式

name = input("Please input your name: ")
age = input("Please input your age: ")
sex = input("Please input your sex: ")

message = '''
Information of %s:
Name:%s
Age:%s
Sex:%s
'''%(name,name,age,sex)
print(message)

輸出結果如下:

Information of Alex:
    Name:Alex
    Age:38
    Sex:girl

    使用單引號('''''')或者雙引號("""""")的方式,這種方式也很方便,我們首先進行定義,把我們需要的格式進行定義,要經常嘗試這幾種格式的方法,這三種方式我都覺得挺好的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM