dataplumber
dataplumber

Reputation: 417

Python List: Replace Double Quotes with Single Quotes

I am trying to insert data to oracle db and the values for the columns are consumed from a list. the list contains several values and for empty values (marked as "" - Double Quotes) it fails. So I would like to change all double quotes in a list to single quotes.

values = ['50.38146', "", "", 'ABC']

Here "" is marked as empty value. I would like to change all Double Double Quotes with Double Single Quotes to represent empty string. Something like this :

values = ['50.38146', '', '', 'ABC']

I tried below but doesn't works :

row1 = []
for x in values:
  if x == "":
    row1.append('')
  else:
    row1.append(x)

Any ideas

Upvotes: 1

Views: 1933

Answers (3)

The reason your code doesn't work is because in the code, you wrote, if x == "",
you are saying that if x equals blank. That doesn't do anything because you are saying, if x equals blank, instead, you need to use x == '""', this tells the program that you want to find the double quotes, and using the single quotes as the string specifier.

So, your code would be this instead:

row1 = []

for x in values:

if x == '""':

    row1.append('')

else:

    row1.append(x)

Upvotes: 0

user13966865
user13966865

Reputation: 468

Get first index of "" and replace it with '' it will replace all the occurences of "" with ''

>>> values = ['50.38146', "", "", 'ABC']
>>> index=values.index("") #get first index of ""
>>> values[index]='' #replaces all "" with ''
>>> values
['50.38146', '', '', 'ABC']

Upvotes: 0

dataplumber
dataplumber

Reputation: 417

Solution is to replace if x == "" with if x == '""'

row1 = []
for x in values:
    if x == '""':
        row1.append('')
    else:
        row1.append(x)
    
print(row1)

values = ['50.38146', '', '', 'ABC']

Upvotes: 0

Related Questions