Python 将字符串与列表的所有成员连接起来,并以逗号分隔显示每个显示结果
Python Concatenate string with all members of a list and display each display result separated by commas
我正在尝试做类似 "conjugator" 的事情。
假设我有一个结尾列表:
endings = ['o', 'es', 'e', 'emos', 'eis', 'em']
我有一个动词词根作为字符串:
root = "com"
我想到的方法是:
for ending in endings:
print root + ending
输出:
como
comes
come
comemos
comeis
comem
但我想要的结果是:
como, comes, come, comemos, comeis, comem
我怎样才能做到这一点(并且每个结果项都没有引号,最后一项后没有逗号)?
您需要列表理解和 str.join()
. 来自文档:
str.join(iterable)
Return a string which is the concatenation of the
strings in the iterable iterable. The separator between elements is
the string providing this method.
>>> root = "com"
>>> endings = ['o', 'es', 'e', 'emos', 'eis', 'em']
>>> verbs = [root + ending for ending in endings]
>>> print ", ".join(verbs)
como, comes, come, comemos, comeis, comem
我正在尝试做类似 "conjugator" 的事情。
假设我有一个结尾列表:
endings = ['o', 'es', 'e', 'emos', 'eis', 'em']
我有一个动词词根作为字符串:
root = "com"
我想到的方法是:
for ending in endings:
print root + ending
输出:
como
comes
come
comemos
comeis
comem
但我想要的结果是:
como, comes, come, comemos, comeis, comem
我怎样才能做到这一点(并且每个结果项都没有引号,最后一项后没有逗号)?
您需要列表理解和 str.join()
. 来自文档:
str.join(iterable)
Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.
>>> root = "com"
>>> endings = ['o', 'es', 'e', 'emos', 'eis', 'em']
>>> verbs = [root + ending for ending in endings]
>>> print ", ".join(verbs)
como, comes, come, comemos, comeis, comem