打印具有连续字母数的字符串

时间:2016-03-17 16:13:27

标签: python string list tuples

我试图打印一个字符串,其中包含每个字母的连续数量,因此字符串应该打印" aaabaaccc"。任何人都可以告诉我哪里出错了,因为我只是python的初学者

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

g = ''

for f in h:

    g = g + f

6 个答案:

答案 0 :(得分:3)

您可以使用Python列表推导来避免字符串连接。

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

这将打印:

aaabaaccc

答案 1 :(得分:1)

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重复字符串n次。

答案 2 :(得分:1)

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)

答案 3 :(得分:0)

您正试图将您的元组(两个项目)打包成一个,这是您无法做到的。

请改为尝试:

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

答案 4 :(得分:0)

Python让你"乘以"数字字符串:

30 times do
  puts "is the page-list present?: #{browser.ul(:class => "page-list").present?}"
  wait .1
end 

所以你可以遍历列表,"乘以"数字的字符串,并以这种方式构建字符串。

>>> 'a' * 5
'aaaaa'

>>> 'ab' * 3
'ababab'

答案 5 :(得分:0)

如果" h"总是会像这样格式化,这是一个oneliner:

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