Home > Enterprise >  How to add a specific character in a list value in Python?
How to add a specific character in a list value in Python?

Time:12-13

I have a list of values that were pulled from a pandas df column - converted to upercase - and one of the values contains "" instead of '' for a value. List looks like so:

('HUAXIA LIFE INSURANCE CORP', 
"PEOPLE'S BANK OF CHINA (PBOC) - GOVERNMENT SECURITIES DEPOSITORY TRUST & CLEARING CO. LTD.", 'BANCA POPOLARE DI SVILUPPO')

I would like to add single quotes in front of the "PEOPLE'S BANK OF CHINA.." value in the list so I can read it in an sql statement.

I tried using replace

str(updated_unique_accts).replace("[",(").replace("]",")").replace("\"","'")

but that didn't work - removes the double quotes and replaces them with single quotes. Any ideas for this?

Desired output

('HUAXIA LIFE INSURANCE CORP', 
'"PEOPLE'S BANK OF CHINA (PBOC) - GOVERNMENT SECURITIES DEPOSITORY TRUST & CLEARING CO. LTD."', 'BANCA POPOLARE DI SVILUPPO')

CodePudding user response:

Considering what you have given, I assume you want the final output as a string. With that in consideration, you just had a slight issue with your code. I added one more replace to handle the end condition. Here you go:

updated_unique_accts = ('HUAXIA LIFE INSURANCE CORP', 
"PEOPLE'S BANK OF CHINA (PBOC) - GOVERNMENT SECURITIES DEPOSITORY TRUST & CLEARING CO. LTD.", 
'BANCA POPOLARE DI SVILUPPO')
print(str(updated_unique_accts).replace("[","(").replace("]",")").replace(", \"",", '\"").replace("\",","\"',"))

OUTPUT:

string substituion

CodePudding user response:

This seems to meet the goal without for loop. The starting output is a tuple as far as python is concerned. Surrounding it with triple quotes makes it a multi-line string. Which can now be processed with .replace().

No for loop is required on the string because of the default replace all.

text = '''('HUAXIA LIFE INSURANCE CORP',"PEOPLE'S BANK OF CHINA (PBOC) - GOVERNMENT SECURITIES DEPOSITORY TRUST & CLEARING CO. LTD.",'BANCA POPOLARE DI SVILUPPO')'''
left_replace = text.replace(',"', ',\'"')
right_replace = left_replace.replace('",', '"\',')
print(right_replace)

('HUAXIA LIFE INSURANCE CORP','"PEOPLE'S BANK OF CHINA (PBOC) - GOVERNMENT SECURITIES DEPOSITORY TRUST & CLEARING CO. LTD."','BANCA POPOLARE DI SVILUPPO')

  • Related