[英]How to repeat individual characters in strings in Python
我知道
"123abc" * 2
评估为"123abc123abc"
,但是有没有一种简单的方法可以将单个字母重复 N 次,例如将"123abc"
转换为"112233aabbcc"
或"111222333aaabbbccc"
?
怎么样:
>>> s = '123abc'
>>> n = 3
>>> ''.join([char*n for char in s])
'111222333aaabbbccc'
>>>
(从生成器表达式更改为列表 comp,因为在 join 内使用列表 comp更快)
一个带有repeat()
、 izip()
和chain()
的替代itertools
-problem-overcomplicating-style 选项:
>>> from itertools import repeat, izip, chain
>>> "".join(chain(*izip(*repeat(s, 2))))
'112233aabbcc'
>>> "".join(chain(*izip(*repeat(s, 3))))
'111222333aaabbbccc'
或者,“我知道正则表达式,我会用它做所有事情”风格的选项:
>>> import re
>>> n = 2
>>> re.sub(".", lambda x: x.group() * n, s) # or re.sub('(.)', r'\1' * n, s) - thanks Eduardo
'112233aabbcc'
当然,不要在实践中使用这些解决方案。
或者另一种方法是使用map
:
"".join(map(lambda x: x*7, "map"))
如果你想重复单个字母,你可以用 n 个字母替换字母,例如
>>> s = 'abcde'
>>> s.replace('b', 'b'*5, 1)
'abbbbbcde'
或者使用正则表达式:
>>> import re
>>> s = '123abc'
>>> n = 3
>>> re.sub('(.)', r'\1' * n, s)
'111222333aaabbbccc'
因为我对所有东西都使用 numpy,所以我们开始:
import numpy as np
n = 4
''.join(np.array(list(st*n)).reshape(n, -1).T.ravel())
@Bahrom 的答案可能比我的更清楚,但只是说这个问题有很多解决方案:
>>> s = '123abc'
>>> n = 3
>>> reduce(lambda s0, c: s0 + c*n, s, "")
'111222333aaabbbccc'
请注意, reduce
不是 python 3 中的内置函数,您必须改用functools.reduce
。
另一种方式:
def letter_repeater(n, string):
word = ''
for char in list(string):
word += char * n
print word
letter_repeater(4, 'monkeys')
mmmmoooonnnnkkkkeeeeyyyyssss
这是我天真的解决方案
text = "123abc"
result = ''
for letters in text:
result += letters*3
print(result)
输出:111222333aaabbbccc
蟒蛇:
def LetterRepeater(times,word) :
word1=''
for letters in word:
word1 += letters * times
print(word1)
word=input('Write down the word : ')
times=int(input('How many times you want to replicate the letters ? '))
LetterRepeater(times,word)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.