Home > Mobile >  How to implement a function which receives a string and replaces all `"` symbols with `'`
How to implement a function which receives a string and replaces all `"` symbols with `'`

Time:03-29


str = input("Something: ")


modified_str = ''


for char in range(0, len(str)):
    # checking if the character at char index is equivalent to 'a'
    if(str[char] == '"'):
        # append $ to modified string
        modified_str  = "'"
    elif(str[char] == "'"):
        modified_str == '"'
    else:
        # append original string character
        modified_str  = str[char]

print("Modified string : ")
print(modified_str)

My output result was: Something: dd"""ddd'''ddd Modified string : dd'''dddddd - but why it doesn't replace ' character

CodePudding user response:

As chepner already mentioned you need to use = instead of == in your elif branch.


You can also shorten the code and implement a slightly different, more pythonic logic:

  1. Find the indices of "
  2. Replace all ' with "
  3. Set all characters at indices found in the first step to '
input = "'test' it or test \"this\""

tmp_idx = [pos for pos, char in enumerate(input) if char == "'"]

result = list(input.replace("\"", "'"))
for idx in tmp_idx:
    result[idx] = "\""
result = "".join(result)

print(result)

This performs the replacement you are looking for:

Input: 'test' it or test "this"

Output: "test" it or test 'this'

CodePudding user response:

This would best be solved with str.translate.

You can create a translation table with str.maketrans which allows you to define it in a few different ways. The most readable in your case is probably to use a dict mapping each char to its translation:

conversion_table = str.maketrans({'"':"'", "'":'"'})

You just need to use the translate method of the string you want to convert with this table as argument:

print('I\'m getting "converted"'.translate(conversion_table))

# I"m getting 'converted'
  • Related