溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python如何格式化字符串

發(fā)布時(shí)間:2021-12-14 17:47:02 來(lái)源:億速云 閱讀:186 作者:小新 欄目:大數(shù)據(jù)

這篇文章主要介紹Python如何格式化字符串,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

代碼實(shí)現(xiàn)

# 格式化字符串
a = 'hello'
print(a)
a = 'abc' + 'haha' + '哈哈'
print(a)
a = 123
print(a)
b = 'Hello %s'%'孫悟空'
print(b)
b = 'hello %s 你好 %s'%('tom','孫悟空')
print(b)
b = 'hello %3.5s'%'abcdefg' # %3.5s字符串的長(zhǎng)度限制在3-5之間
print(b)
b = 'hello %s'%123.456
print(b)
b = 'hello %.2f'%123.456
print(b)
b = 'hello %d'%123.95
print(b)
b = '呵呵'
print(b)
c = f'hello {a} '
print(f'c = {c}')

代碼運(yùn)行輸出:

hello

abchaha哈哈

123

Hello 孫悟空

hello tom 你好 孫悟空

hello abcde

hello 123.456

hello 123.46

hello 123

呵呵

c = hello 123 呵呵


 

程序分析

# 字符串之間也可以進(jìn)行加法運(yùn)算

# 如果將兩個(gè)字符串進(jìn)行相加,則會(huì)自動(dòng)將兩個(gè)字符串拼接為一個(gè)

# 字符串不能和其他的類(lèi)型進(jìn)行加法運(yùn)算,如果做了會(huì)出現(xiàn)異常TypeError: must be str, not int

#print("a = "+a)  這種寫(xiě)法在Python中不常見(jiàn)

# 在創(chuàng)建字符串時(shí),可以在字符串中指定占位符

# %s 在字符串中表示任意字符

# %f 浮點(diǎn)數(shù)占位符

# %d 整數(shù)占位符

# 格式化字符串,可以通過(guò)在字符串前添加一個(gè)f來(lái)創(chuàng)建一個(gè)格式化字符串

# 在格式化字符串中可以直接嵌入變量

以上是“Python如何格式化字符串”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI