Reputation: 21
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
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
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
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
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
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
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