Python中應該使用%還是format來格式化字串?

來源:互聯網
上載者:User

標籤:格式化   convert   https   form   orm   mat   python3   方法   argument   

Python中格式化字串目前有兩種陣營:%和format,我們應該選擇哪種呢?

 

自從Python2.6引入了format這個格式化字串的方法之後,我認為%還是format這根本就不算個問題。不信你往下看。

 

%的劣勢:

# 定義一個座標值c = (250, 250)# 使用%來格式化s1 = "敵人座標:%s" % c

上面的代碼很明顯會拋出一個如下的TypeError:

TypeError: not all arguments converted during string formatting

像這類格式化的需求我們需要寫成下面醜陋的格式才行:

 

# 定義一個座標值c = (250, 250)# 使用%醜陋的格式化...s1 = "敵人座標:%s" % (c,)

 

而使用format就不會存在上面的問題:

 

 

# 定義一個座標值c = (250, 250)# 使用format格式化s2 = "敵人座標:{}".format(c)

 

很顯然,上面這一個理由就已經足夠讓你在以後的項目中使用format了。

在Python3.6中加入了f-strings:

In[2]: name = "Q1mi"In[3]: age = 18In[4]: f"My name is {name}.I‘m {age}"Out[4]: "My name is Q1mi.I‘m 18"

 

Python中應該使用%還是format來格式化字串?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.