将列表的元素格式化为特定字符串

时间:2017-07-04 01:56:34

标签: python string list

我试图获取术语列表并以特定格式输出它们。

例如,我有一个动词列表:

verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']

我希望我的输出是一个字符串,其中列表中的每个项目也是一个字符串,由|

描绘
magic(verbs)

输出:

"eat" | "run" | "jump" | etc.

我尝试过使用.join方法,但这只是给了我一大串由管道分隔的术语,而不是我想要的。有任何想法吗?我对Python很陌生,如果这是令人难以置信的低眉或其他地方已经回答的话,我很抱歉。

5 个答案:

答案 0 :(得分:3)

verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
x=(' | '.join('"' + item + '"' for item in verbs))
print(x)

你可以看到ouput here

答案 1 :(得分:2)

尝试:

verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
print("|".join(['"'+e+'"' for e in verbs]))

输出:

"eat"|"run"|"jump"|"play"|"walk"|"talk"|"send"

答案 2 :(得分:2)

这样做你想要的:

def magic(terms):
    print(' | '.join('"%s"' % term for term in terms))

verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
magic(verbs)  # -> "eat" | "run" | "jump" | "play" | "walk" | "talk" | "send"

答案 3 :(得分:2)

verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']

def magic(s):
    return ' | '.join('"%s"' % x for x in s)

print(magic(verbs))
# "eat" | "run" | "jump" | "play" | "walk" | "talk" | "send"

答案 4 :(得分:0)

在每个引号括起的动词之间,放一个管道:

" | ".join('"{0}"'.format(verb) for verb in verbs)
>>> verbs = ['eat', 'run', 'jump', 'play', 'walk', 'talk', 'send']
>>> print(" | ".join('"{0}"'.format(verb) for verb in verbs))
"eat" | "run" | "jump" | "play" | "walk" | "talk" | "send"