簡體   English   中英

如何將可變長度列表插入字符串

[英]How to insert variable length list into string

我有一個我認為是 Python 中的基本問題:

我有一個長度可變的列表,我需要將其插入字符串以供以后使用。 格式化很簡單,我只需要在每個名稱之間使用逗號,直到 nameN 和名稱周圍的括號。

List = ['name1', 'name2' .... 'nameN']
string = "Their Names are <(name1 ... nameN)> and they like candy.

例子:

List = ['tom', 'jerry', 'katie']
print(string)
Their Names are (tom, jerry, katie) and they like candy.

對此有什么想法嗎? 謝謝您的幫助!

# Create a comma-separated string with names
the_names = ', '.join(List) # 'tom, jerry, katie'

# Interpolate it into the "main" string
string = f"Their Names are ({the_names}) and they like candy."

有很多方法可以實現這一目標。 您可以使用類似於@ForceBru 中的示例的 print + format + join。 使用格式將使其與 Python2 和 Python3 兼容。

names_list = ['tom', 'jerry', 'katie']

"""
Convert the list into a string with .join (in this case we are separating with commas)
"""
names_string = ', '.join(names_list)
# names_string == "tom, katie, jerry"

# Now add one string inside the other:
string = "Their Names are ({}) and they like candy.".format(names_string)
print(string)

>> Their Names are (tom, jerry, katie) and they like candy.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM