Reputation:
I need to create a function in Python to iterate over a given string, in this case 'hello-world' and have an output where characters in the string that do not have pairs, are printed with a paired character.
Input String: hello-world
Output String: hheello--wworrldd
So for this example, I only want to repeat the characters 'h' 'e' 'w' 'r' 'd' and not repeat 'l' or 'o' I tried this function, and it did repeat the characters, but I am not sure how to isolate only the characters that do not have a pair in the string.
def character_pair(n, input_string):
word = ''
for char in list(input_string):
word += char * n
print (word)
character_pair(2, 'hello-world')
This was my output: hheelllloo--wwoorrlldd
Upvotes: 0
Views: 671
Reputation: 1
def repeatChar(n, sentence):
words = ''
for char in list(sentence):
word += char * n
print(words)
sentence = input('Here you can write.. ')
repeatChar(2, sentence)
Upvotes: 0
Reputation: 563
string = 'hello-world'
new_word = ''
for each_char in string:
if string.count(each_char) > 1:
new_word += each_char
else:
new_word += each_char * 2
Upvotes: 0
Reputation: 781340
Use collections.Counter
to count the repetitions of each character. Then check if the count is 1 before multiplying the character.
import collections
def character_pair(n, input_string):
counts = collections.Counter(input_string)
word = ''
for char in input_string:
if counts[char] > 1:
word += char
else:
word += char * n
print (word)
character_pair(2, 'hello-world')
Upvotes: 1