0

I'm trying to take a list of terms and output them in a specific format.

For example, I have a list of verbs:

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

and I want my output to be a string, where each item in the list is also a string, delineated by a |

magic(verbs)

output:

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

I've tried using the .join method, but that just gives me one big string of the terms separated by pipes, instead of what I want. Any ideas? I'm pretty new to Python and I'm sorry if this is incredibly low-brow or something that has been answered elsewhere.

2
  • 1
    Use a list comprehension that puts the quotes around each item, then use .join() to join them with a pipe. Commented Jul 4, 2017 at 1:57
  • Thanks everyone! Commented Jul 4, 2017 at 3:08

5 Answers 5

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

you can see ouput here

Sign up to request clarification or add additional context in comments.

Comments

2

Try with:

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

Output:

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

Comments

2

This does what you want:

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"

Comments

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"

Comments

0

Between each quote-enclosed verb, put a pipe:

" | ".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"

1 Comment

Please explain the downvote so I can improve the answer. Blind downvotes just seem spiteful. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.