简体   繁体   English

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

[英]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". 我正在尝试打印包含每个字母连续数量的字符串,因此该字符串应打印“ aaabaaccc”。 Can anyone tell me where i'm going wrong please as i'm only a beginner in python 谁能告诉我我要去哪里错了,因为我只是python的初学者

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

g = ''

for f in h:

    g = g + f

You can use a Python list comprehension to do this which avoids string concatenation. 您可以使用Python列表推导来避免字符串连接。

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

This will print: 这将打印:

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 repeats String n times. 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)

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

Python let's you "multiply" strings by numbers: Python让您将字符串乘以数字:

>>> '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

如果“ h”总是要这样格式化,那么一个单行代码是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM