Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用Python编写一个函数,该函数接受一个字符串并返回一个新字符串,即所有字符都重复的原始字符串?_Python_String_Function_Return Value - Fatal编程技术网

如何用Python编写一个函数,该函数接受一个字符串并返回一个新字符串,即所有字符都重复的原始字符串?

如何用Python编写一个函数,该函数接受一个字符串并返回一个新字符串,即所有字符都重复的原始字符串?,python,string,function,return-value,Python,String,Function,Return Value,我试图编写一个函数,返回一个字符串,该字符串是带有双字符的输入字符串。例如,如果输入为“hello”,则函数应返回“hheelllo”。我一直在尝试,但似乎找不到编写函数的方法。非常感谢您的帮助。使用简单的生成器: s = 'hello' ''.join(c+c for c in s) # returns 'hheelllloo' >>> s = 'hello' >>> ''.join(c * 2 for c in s) 'hheelllloo' 使用:

我试图编写一个函数,返回一个字符串,该字符串是带有双字符的输入字符串。例如,如果输入为“hello”,则函数应返回“hheelllo”。我一直在尝试,但似乎找不到编写函数的方法。非常感谢您的帮助。

使用简单的生成器:

s = 'hello'
''.join(c+c for c in s)

# returns 'hheelllloo'
>>> s = 'hello'
>>> ''.join(c * 2 for c in s)
'hheelllloo'
使用: 重复“你好”,2 输出:“hheelloo”

因为字符串是不可变的,所以像repeatChars方法中看到的那样将它们连接在一起不是一个好主意。如果您正在处理的文本的长度很短,比如“hello”,这没关系,但是如果您正在传递“superfragilisticexpialidocious”或更长的字符串。。。你明白了。因此,作为替代方案,我将以前的代码与@Roman Bodnarchuk的代码合并

替代方法:


为什么??阅读此文:

您能分享您迄今为止的尝试吗?我们可以试着纠正这一点。我认为,这不是一个列表理解,而是一个生成器表达式。这两种递归的使用都很好,为什么在Python的实际问题中使用递归是浪费时间的。不过,对于学习思考它是如何工作的来说,它确实是合适的。
def repeatChars(text, numOfRepeat):
    ans = ''
    for c in text:
        ans += c * numOfRepeat
    return ans
def repeatChars(text, numOfRepeat):
    return ''.join([c * numOfRepeat for c in text])
>>> s = "hello"
>>> "".join(map(str.__add__, s, s))
'hheelllloo'
def doublechar(s):
    if s:
        return s[0] + s[0] + doublechar(s[1:])
    else:
        return ""