[英]Most pythonic way to add object to string?
我有Java背景,正在嘗試學習Python。 假設我有一個數組,我想打印出它的長度以及一個字符串。 在Java中,我可以這樣做:
System.out.println("The length of the list is " + myList.length);
但是,我不知道在Python中可以接受的方法是什么。 我會這樣做嗎:
print("The length of the list is " + str(len(my_list)))
或這個?:
print("The length of the list is {x}".format(x=len(my_list)))
做這種事情的最公認的,pythonic方法是什么? 如果是這樣,為什么?
在Python≥3.6中,您還可以執行以下操作:
print(f'The length of the list is {len(my_list)}')
文件: https : //docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals
如果要將自定義類的實例插入到字符串中,只需確保它具有__str__
方法即可。
有四種方法可以將對象的字符串表示形式放入字符串中,但在這種情況下,我不推薦使用以下任何一種方法:
print("The length of the list is " + str(len(my_list)))
print("The length of the list is %d" % len(my_list))
print("The length of the list is {}".format(len(my_list)))
print(f"The length of the list is {len(my_list)}")
而是利用print
可以為您完成的事實!
print("The length of the list is", len(my_list))
請注意,您不需要將其強制轉換為字符串,並且我從字符串文字中刪除了尾隨空格: print
自動在其參數之間放置一個空格。
實際上,最好的方法取決於您,但是Python建議使用.format()
和Java中的System.out.printf
一樣,您也可以編寫
print('The length of the list is %d' % len(my_list))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.