[英]How do you write a function in Python that takes a string and returns a new string that is the original string with all of the characters repeated?
I am trying to write a function that returns a string that is the inputted string with double characters. 我正在尝试编写一个函数,该函数返回一个字符串,该字符串是带有双字符的输入字符串。 For example, if the input was 'hello', then the function should return 'hheelllloo'. 例如,如果输入为“ hello”,则函数应返回“ hheelllloo”。 I have been trying but I can't seem to find a way to write the function. 我一直在尝试,但是似乎找不到找到编写函数的方法。 Any help would be greatly appreciated--Thanks. 任何帮助将不胜感激-谢谢。
With a simple generator: 使用简单的生成器:
>>> s = 'hello'
>>> ''.join(c * 2 for c in s)
'hheelllloo'
def repeatChars(text, numOfRepeat):
ans = ''
for c in text:
ans += c * numOfRepeat
return ans
To use: 使用方法:
repeatChars('hello', 2) repeatChars('hello',2)
output: 'hheelllloo' 输出: 'hheelllloo'
Since strings are immutable, it's not a good idea to concatenate them together as seen in the repeatChars method. 由于字符串是不可变的,所以将它们串联在一起并不是一个好主意,如repeatChars方法所示。 It's okay if the text you're manipulating has short length like 'hello' but if you're passing 'superfragilisticexpialidocious' (or longer strings)... You get the point. 如果您要处理的文本的长度短(例如“ hello”)也可以,但是如果您传递的是“ superfragilisticexpialidocious”(或更长的字符串),那没关系。 So as an alternative, I've merged my previous code with @Roman Bodnarchuk's code. 因此,作为替代方案,我将之前的代码与@Roman Bodnarchuk的代码合并。
Alternate method: 替代方法:
def repeatChars(text, numOfRepeat):
return ''.join([c * numOfRepeat for c in text])
Why? 为什么? Read this: Efficient String Concatenation in Python 阅读本文: Python中的高效字符串连接
s = 'hello'
''.join(c+c for c in s)
# returns 'hheelllloo'
>>> s = "hello"
>>> "".join(map(str.__add__, s, s))
'hheelllloo'
def doublechar(s):
if s:
return s[0] + s[0] + doublechar(s[1:])
else:
return ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.