字符串字母乘以数字位数

时间:2019-11-25 14:23:59

标签: python-3.x

我想将字符串的字母乘以数字的位数。例如,单词“ number”和数字“ 123” 输出将是“ nuummmbeerrr”。如何创建执行此操作的功能?我的代码没有用,因为它不起作用。

我只有这个

def new_word(s):
    b=""
    for i in range(len(s)):
        if i % 2 == 0:
            b = b + s[i] * int(s[i+1])    

return b

对于new_word('a3n5z1')输出为 aaannnnnz

3 个答案:

答案 0 :(得分:3)

使用列表推导,不使用itertools

number = 123
word = "number"

new_word = "".join([character*n for (n, character) in zip(([int(c) for c in str(number)]*len(str(number)))[0:len(word)], word)])

print(new_word)

# > 'nuummmbeerrr'

它的作用(更多细节)如下:

number = 123
word = "number"

# the first trick is to link each character in the word to the number that we want
# for this, we multiply the number as a string and split it so that we get a list...
# ... with length equal to the length of the word
numbers_to_characters = ([int(c) for c in str(number)]*len(str(number)))[0:len(word)]

print(numbers_to_characters)

# > [1, 2, 3, 1, 2, 3]

# then, we initialize an empty list to contain the repeated characters of the new word
repeated_characters_as_list = []

# we loop over each number in numbers_to_letters and each character in the word
for (n, character) in zip(numbers_to_characters, word):
    repeated_characters_as_list.append(character*n)

print(repeated_characters_as_list)

# > ['n', 'uu', 'mmm', 'b', 'ee', 'rrr']

new_word = "".join(repeated_characters_as_list)

print(new_word)

# > 'nuummmbeerrr'

答案 1 :(得分:1)

这将解决您的问题,可以随时对其进行修改以满足您的需求。

from itertools import cycle

numbers = cycle("123")
word = "number"

output = []

for letter in word:
  output += [letter for _ in range(int(next(numbers)))]

string_output = ''.join(output)

编辑:

由于您是初学者,即使我建议阅读itertools模块,因为它是处理此类问题的正确工具,但它对您来说更容易理解。

number = "123"
word = "number"


output = []
i = 0

for letter in word:
  if(i == len(number)):
    i = 0
  output += [letter for _ in range(int(number[i]))]
  i += 1

string_output = ''.join(output)
print(string_output)

答案 2 :(得分:1)

您可以使用zip将每个数字与单词中的相应字符匹配(对于单词较长的情况,请使用itertools.cycle),然后将char乘以该数字,最后加入到单个字符串。

尝试一下:

from itertools import cycle

word = "number"
number = 123

number_digits = [int(d) for d in str(number)]

result = "".join(letter*num for letter,num in zip(word,cycle(number_digits)))
print(result)

输出:

nuummmbeerrr