[SOLVED] How to replace a character of a string using for loop in python?


I’m trying to make a code that finds special characters and replace them in to *.
For example:

L!ve l@ugh l%ve

This should be changed as

L*ve l*ugh l*ve

Here it’s what I tried so far

a = input()
spe = "+=/_(*&^%$#@!-.?)"
for i in a:
    if i in spe:
        b = a.replace(i,"*")
        b = i

This returns something like this

Lve lugh lve

Why I’m getting like this?
And how to solve this issue?


You’re trying to modify the whole string whereas you should only work on the character.

Modifying your code, this would be:

a = '(L!ve l@ugh l%ve)'
spe = set("+=/_(*&^%$#@!-.?)") # using a set for efficiency

for char in a:
    if char in spe:
        print('*', end='')
        print(char, end='')

output: *L*ve l*ugh l*ve*

A more pythonic way would be:

spe = set("+=/_(*&^%$#@!-.?)")
print(''.join(['*' if c in spe else c  for c in a]))

Answered By – mozway

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *