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

Recommended Answers

All 2 Replies

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.

Without module re ...

word = 'Cat'
result = ''.join('a' for c in word)
print(result)  # aaa
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.