![](/img/trans.png)
[英]How to merge consecutive letters and consecutive numbers from a string to a list separetely?
[英]Printing a string with consecutive numbers of letters
我正在尝试打印包含每个字母连续数量的字符串,因此该字符串应打印“ aaabaaccc”。 谁能告诉我我要去哪里错了,因为我只是python的初学者
h = [("a", 3), ("b", 1), ("a", 2), ("c", 3)]
g = ''
for f in h:
g = g + f
您可以使用Python列表推导来避免字符串连接。
print ''.join(letter * count for letter, count in [("a", 3), ("b", 1), ("a", 2), ("c", 3)])
这将打印:
aaabaaccc
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
重复String n次。
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)
您正在尝试将元组(两个项目)拆成一个包装,而这是做不到的。
尝试以下方法:
for letter, multiplier in h:
g += letter * multiplier
Python让您将字符串乘以数字:
>>> 'a' * 5
'aaaaa'
>>> 'ab' * 3
'ababab'
因此,您可以遍历列表,将字符串乘以数字,然后以这种方式构建字符串。
>>> h = [("a", 3), ("b", 1), ("a", 2), ("c", 3)]
>>> g = ''
>>> for letter, number in h:
... g += letter * number
...
>>> print(g)
aaabaaccc
如果“ h”总是要这样格式化,那么一个单行代码是:
g = "".join([i[0]*i[1] for i in h])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.