如何将可变长度列表插入字符串

发布于 2025-02-10 03:53:56 字数 410 浏览 0 评论 0原文

我认为我认为是Python中的一个基本问题:

我有一个列表,该列表的长度可以变化,我需要将其插入字符串中以备后用。 格式很简单,我只需要在名称围绕名称的每个名称和括号的每个名称之间进行逗号。

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.

对此有什么想法吗?感谢您的帮助!

I have what I think is a basic question in Python:

I have a list that can be variable in length and I need to insert it into a string for later use.
Formatting is simple, I just need a comma between each name up to nameN and parenthesis surrounding the names.

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

Example:

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

Any ideas on this? Thanks for the help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

微凉 2025-02-17 03:53:56
# 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."
# 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."
千柳 2025-02-17 03:53:56

有很多方法可以实现这一目标。
您可以使用print +格式 +与@forcebru的示例相似。
使用格式可以使其与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.

There are numerous ways to achieve that.
You could use print + format + join similar to the example from @ForceBru.
Using format would make it compatible with both Python2 and 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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文