How to double a char in a string?

巧了我就是萌 提交于 2021-01-29 06:56:12

问题


I am trying to write a function that takes two arguments, a string and a letter. The function should then double the number of letter in the string. For example:

double_letters("Happy", "p")
Happppy

what i have done so far;

def double_letter(strng, letter):
 new_word = ""
    for char in strng:
        if char == letter:
            pos = strng.index(char)
            new_word = letter+strng[pos:]

But this is giving me the output: pppy

how can i change the function to get the output: Happppy?


回答1:


Use string.replace

string = 'happy'
letter = 'p'
string = string.replace(letter, letter + letter)
print string



回答2:


You could use join and iterate through the characters in your string:

def double_letters(word, letter):
    return "".join(2*i if i == letter else i for i in word)


来源:https://stackoverflow.com/questions/22605967/how-to-double-a-char-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!