fugu
fugu

Reputation: 6578

print elements in list as concatenated string

I have a simple dictionary:

convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}

and list

letters = ('a', 'b', 'c', 'd')

I want to iterate over each element in the list, and use it as a lookup in my dictionary, and print the value as a concatenated string. I'm using:

for c in letters:
    print convert[c],

which outputs:

1 2 3 4

How can I remove the spaces (in v.2.7.10) in the print statement to get:

1234

Upvotes: 2

Views: 936

Answers (5)

Tonechas
Tonechas

Reputation: 13723

To get rid of the extra spaces introduced by print you could write data to standard output using sys.stdout.write():

In [55]: letters = ('a', 'b', 'c', 'd')

In [56]: convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}

In [57]: import sys

In [58]: for letter in letters: sys.stdout.write(convert[letter])
1234

As a side note, most of the solutions proposed here (mine included) produce the expected output for the input data you provided, but see what happens if letters contains a letter (such as 'e') that is not a key in convert:

In [59]: letters = ('a', 'b', 'c', 'd', 'e')

In [60]: print ''.join(str(convert[letter]) for letter in letters)
Traceback (most recent call last):

  File "<ipython-input-60-da3963dcc14b>", line 1, in <module>
    print ''.join(str(convert[letter]) for letter in letters)

  File "<ipython-input-60-da3963dcc14b>", line 1, in <genexpr>
    print ''.join(str(convert[letter]) for letter in letters)

KeyError: 'e'

To avoid this, I recommend you to use dict.get() as this method returns a default value ('' in the example below) instead of raising an error when the key is not in the dictionary:

In [61]: print ''.join(str(convert.get(letter, '')) for letter in letters)
1234

Upvotes: 0

Alex W
Alex W

Reputation: 38183

Just wanted to add an alternative that uses reduce, although it's not necessarily more readable, it may be more flexible later on. If you need to change the code to do something else, you can just adjust the lambda function:

>>> print reduce(lambda x,y: str(x)+str(y),[convert[z] for z in letters])
1234

or to be more readable:

>>> def concat_letters(x,y):
    return str(x)+str(y)

>>> print reduce(concat_letters,[convert[z] for z in letters])
1234

Upvotes: 0

Pabitra Pati
Pabitra Pati

Reputation: 477

Try this out :-

>>> convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
>>> letters = ('a', 'b', 'c', 'd')
>>> result = ''
>>> for i in letters:
        result += str(convert[i])  # Since you want concatenated string
>>> print result
'1234'

Or using list comprehension :-

>>> convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
>>> letters = ('a', 'b', 'c', 'd')
>>> ''.join([str(convert[i]) for i in letters])
'1234'

Upvotes: 1

Iron Fist
Iron Fist

Reputation: 10951

If all you want is to print only and you don't need the end result, then you can use the arg of print method:

>>> from __future__ import print_function
>>> for c in letters:
        print(convert[c], sep='', end='')


1234

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81594

Use join with a generator expression. Note that you have to explicitly convert to str when using this method:

convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
letters = ('a', 'b', 'c', 'd')
print ''.join(str(convert[c]) for c in letters)
>> 1234 

UPDATE

If you want to do it using an explicit for loop, you can create a list of strings, appending to that and calling join outside the loop. I'm using a list since it is more efficient because strings are immutable:

output_list = []
for c in letters:
    # do other stuff
    output_list.append(str(convert[c]))
print ''.join(output_list)

Upvotes: 4

Related Questions