首页 > 解决方案 > How to duplicate each character in a string

问题描述

How would I repeat a every character in a string twice?

Expected Output

input_string = "hello"

output_string = "hheelllloo"

My Code

def double_char(string):
    for i in string:
        # Place code here

def main():
    user_string = input()
    print(double_char(user_string))


main()

How can I complete the function double_char(string)?

标签: pythonstringfunction

解决方案


如果您想多次复制一个字符串,比如说 2,您可以这样做。

s = "a"
double_s = s*2

然后你可以在一个字符串中逐个字符地迭代字符:

for s in my_string:
  # Here I do something with s, like for example duplicate it

因此,将这两种方法混合在一起会累积在字符串中重复的字符:

def double_char(string):
    res = ""
    for i in string:
        res += i*2
    return res

推荐阅读