DaisyMaisy
DaisyMaisy

Reputation: 21

Printing a string with consecutive numbers of letters

I'm trying to print a string which has consecutive amounts of each of the letters, so the string should print "aaabaaccc". Can anyone tell me where i'm going wrong please as i'm only a beginner in python

h = [("a", 3), ("b", 1), ("a", 2), ("c", 3)]

g = ''

for f in h:

    g = g + f

Upvotes: 2

Views: 1020

Answers (6)

snakecharmerb
snakecharmerb

Reputation: 55834

Python let's you "multiply" strings by numbers:

>>> 'a' * 5
'aaaaa'

>>> 'ab' * 3
'ababab'

So you can loop over the list, "multiply" the strings by the numbers, and build the string that way.

>>> h = [("a", 3), ("b", 1), ("a", 2), ("c", 3)]
>>> g = ''
>>> for letter, number in h:
...     g += letter * number
... 
>>> print(g)
aaabaaccc

Upvotes: 0

Jeremy Weirich
Jeremy Weirich

Reputation: 387

If "h" is always going to be formatted like that, a oneliner for this is:

g = "".join([i[0]*i[1] for i in h])

Upvotes: 0

Martin Evans
Martin Evans

Reputation: 46779

You can use a Python list comprehension to do this which avoids string concatenation.

print ''.join(letter * count for letter, count in [("a", 3), ("b", 1), ("a", 2), ("c", 3)])

This will print:

aaabaaccc

Upvotes: 3

Imtiaz Raqib
Imtiaz Raqib

Reputation: 375

h = [("a", 3), ("b", 1), ("a", 2), ("c", 3)]

g = ''

for i, j in h:     # For taking the tuples into consideration


    g += i * j

print(g)  # printing outside for loop so you get the final answer (aaabccc)

Upvotes: 1

riteshtch
riteshtch

Reputation: 8769

h = [("a", 3), ("b", 1), ("a", 2), ("c", 3)]
g = ''
for char, count in h:
    #g = g + f  #cant convert tuple to string implicitly
    g=g+char*count
print(g)

String*n repeats String n times.

Upvotes: 1

Pep_8_Guardiola
Pep_8_Guardiola

Reputation: 5252

You are trying to unpack your tuple (two items) into one, which you can't do.

Try this instead:

for letter, multiplier in h:
    g += letter * multiplier

Upvotes: 0

Related Questions