亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有Python相當于Ruby的字符串插值?

有沒有Python相當于Ruby的字符串插值?

冉冉說 2019-08-06 15:17:49
有沒有Python相當于Ruby的字符串插值?Ruby示例:name = "Spongebob Squarepants"puts "Who lives in a Pineapple under the sea? \n#{name}."成功的Python字符串連接對我來說似乎很冗長。
查看完整描述

3 回答

?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

Python 3.6將添加類似于Ruby的字符串插值的文字字符串插值。從該版本的Python(計劃于2016年底發布)開始,您將能夠在“f-strings”中包含表達式,例如

name = "Spongebob Squarepants"print(f"Who lives in a Pineapple under the sea? {name}.")

在3.6之前,你可以得到最接近的

name = "Spongebob Squarepants"print("Who lives in a Pineapple under the sea? %(name)s." % locals())

%運算符可用于Python中的字符串插值。第一個操作數是要插值的字符串,第二個操作數可以有不同的類型,包括“映射”,將字段名稱映射到要插值的值。在這里,我使用局部變量字典locals()將字段名稱映射name為其值作為局部變量。

使用.format()最新Python版本方法的相同代碼如下所示:

name = "Spongebob Squarepants"print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))

還有string.Template班級:

tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")print(tmpl.substitute(name="Spongebob Squarepants"))


查看完整回答
反對 回復 2019-08-06
?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

我開發了interpy包,它可以在Python啟用字符串插值。

只需通過安裝即可pip install interpy。然后,# coding: interpy在文件的開頭添加行!

例:

#!/usr/bin/env python# coding: interpyname = "Spongebob Squarepants"print "Who lives in a Pineapple under the sea? \n#{name}."


查看完整回答
反對 回復 2019-08-06
  • 3 回答
  • 0 關注
  • 575 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號