简体   繁体   中英

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'. 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)
output: 'hheelllloo'

Since strings are immutable, it's not a good idea to concatenate them together as seen in the repeatChars method. 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. So as an alternative, I've merged my previous code with @Roman Bodnarchuk's code.

Alternate method:

def repeatChars(text, numOfRepeat):
    return ''.join([c * numOfRepeat for c in text])

Why? Read this: Efficient String Concatenation in 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 ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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