user1718826
user1718826

Reputation: 347

Convert list of strings to space-separated string

I am using underscores to represent the length of a unknown word. How can I print just the underscores without the brackets that represent the list?

Basically, if I have a list of the form ['_', '_', '_', '_'], I want to print the underscores without printing them in list syntax as "_ _ _ _"

Upvotes: 9

Views: 25620

Answers (3)

James Waldby - jwpat7
James Waldby - jwpat7

Reputation: 8711

The previously-mentioned join solution (like in following line) is a reasonable solution:

print ''.join(['_', '_', '_', '_'])
____

But also note you can use reduce() to do the job:

print reduce(lambda x,y: x+y, ['_', '_', '_', '_'])
____

After import operator you can say:

print reduce(operator.add, ['_', '_', '_', '_'])
____

Upvotes: 1

chimpsarehungry
chimpsarehungry

Reputation: 1821

In [1]: my_dashes = ['_', '_', '_', '_']

In [2]: str(my_dashes).translate(None, '[],\'')
Out[2]: '_ _ _ _'

Add an extra space in the deletechars string to put the dashes together.

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 114025

Does this work for you

>>> my_dashes = ['_', '_', '_', '_']
>>> print ''.join(my_dashes)
____
>>> print ' '.join(my_dashes)
_ _ _ _

Upvotes: 38

Related Questions