问题
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