0

Hi,

I want to replace all the character in my string with 'aaaa' as many number of times as there are occurence of the character. For eg. if my string is "cat", output should be "aaa" and if its "hello" output should be "aaaaa".
As of now, I am using
result = re.sub(r'([\w.-]+)[a-zA-Z]', 'a','Cat', count=0)

Its returning :
a

I want it should return 'a' as many number of times the characters are repeating, i.e. aaa

3
Contributors
2
Replies
17
Views
4 Years
Discussion Span
Last Post by vegaseat
1

Currently you have a regex that matches the whole string and then replace that with 'a'. So the whole string is going to be replaced with a single 'a'.

If all you want is to replace every character with one 'a' per character, just use a regex that matches a single character. If there are no special requirements on the characters, you can just do:

result = re.sub('.', 'a', 'Cat')

The count = 0 is unnecessary because that's the default.

1

Without module re ...

word = 'Cat'
result = ''.join('a' for c in word)
print(result)  # aaa
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.