'Replace each special symbol with # in the following string

import string 
str1 = '/*dave is @architect & telephone!!'
symbols = string.punctuation

    for char in str1:
        if char in symbols:
            str2 = str1.replace(char,"#")
    print(str2)

thats what i tried and the result is:

/*dave is @architect & telephone##

cant seem to understand why its only changing the last 2 chars



Solution 1:[1]

The problem in your code is.

After this line if char in symbols: you change str2 to str1.replace(char,"#") here str1 is the original string, not the modified string. So you need to use the below code. In You code you can try print(str1) before str1.replace(char,"#") this line to check if the str1 is change or the same as original.

import string 
str1 = '/*dave is @architect & telephone!!'
str2 = str1
symbols = string.punctuation

for char in str1:
    if char in symbols:
        str2 = str2.replace(char,"#")
print(str2)

You can also use list comprehension.

import string 
str1 = '/*dave is @architect & telephone!!'
symbols = string.punctuation
str2 = ''.join(['#' if char in symbols else char for char in str1])
print(str2)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1