Home > Software engineering >  How to replace a character of a string using for loop in python?
How to replace a character of a string using for loop in python?

Time:03-07

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,"*")
    else:
        b = i
        print(b,end="")

This returns something like this

Lve lugh lve

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

CodePudding user response:

A simple way to do it:

import string

all_chars = string.ascii_letters

a = 'L!ve l@ugh l%ve'

for item in a:
    if item ==' ':
        pass
    elif item not in all_chars:
        item='*'
        
    print(item, end="")

CodePudding user response:

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='')
    else:
        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]))

CodePudding user response:

When you reach the if statement and if meets the condition it goes into the branch and executes. If all you want to do is print the statement you could run:

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

but you could also save it as a string

a = input()
new_string = ""
spe = " =/_(*&^%$#@!-.?)"
for i in a:
    if i in spe:
        new_string  = "*"
    else:
        new_string  = i
print(new_string)

CodePudding user response:

As another alternative, you could try a regular expression. Here are two potential approaches depending on how you want to define your set of characters:

import re
print(re.sub('[^a-zA-Z0-9\s]', '*', "L!ve l@ugh l%ve"))
print(re.sub("[$& ,:;=?@#|'<>.^*()%!-]", '*', "L!ve l@ugh l%ve"))
# L*ve l*ugh l*ve

CodePudding user response:

There are two problems in your script:

  • if the special characters are found you replace them in b and not in I
  • you only print if the special characters are not found.
    Try:
a = "L!ve l@ugh l%ve"
spe = " =/_(*&^%$#@!-.?)"
for i in a:
    if i in spe:
        b = i.replace(i,"*")
    else:
        b = i
    print(b,end="")
  • Related