Home > Blockchain >  Python replacing one character with 2 characters
Python replacing one character with 2 characters

Time:06-07

I'm trying to use Python to generate a SQL statement, so I can add new rows of data to a table. However, within the data, there are values that contain an apostrophe ('), which causes problems since the sql statement contains the strings in apostrophes as well.

I don't know how many apostrophes will be in the strings exactly, as each string has been shown to have 0, 1, 2, or more.

To make the string SQL friendly, I need to change every apostrophe to have a second apostrophe directly after it. So, instead of 'Molly's cat is blue', I need 'Molly''s cat is blue'. Keep in mind, this is 2 apostrophes (''), not a single quotation mark (").

A good string to use for testing would be 'That's John's Sister's Cat!', I need to find a way to transform that string into 'That''s John''s Sister''s Cat!' that is not too intense, since this method will be iterating over a large quantity of rows.

Any help would be greatly appreciated

CodePudding user response:

Try this:

myString = 'That\'s John\'s Sister\'s Cat!'

myString_to_arr = list(myString)

i = 0
for char in myString_to_arr:
    if char == "'":
        myString_to_arr[i] = "\"\""
    i  = 1

print("".join(myString_to_arr))

CodePudding user response:

Try the string.replace() method.

item = "That's John's Sister's Cat!"
item = item.replace("'","''")

>>> "That''s John''s Sister''s Cat!"
  • Related