python3替换'字符串中的'

问题描述 投票:0回答:1

我试图清理包含任何'&#39的文本字符串(其中包括;但是如果我在这里添加它你将再次看到'。因为ANSI也由stackoverflow编码。字符串内容包含',当它在那里时是一个错误。

当我将字符串插入我的数据库时,我收到此错误:

psycopg2.ProgrammingError:在“s”第1行或附近的语法错误:1 ...已经开始搜索先生。 whitnell的

原始字符串如下所示:

...a search for mr. whitnell&#39s...

要删除'&#39 ;,我使用:

stripped_content = stringcontent.replace("'","")

stripped_content = stringcontent.replace("&#39 ;","")

欢迎任何建议,最好的问候

string python-3.x postgresql
1个回答
1
投票

当你尝试replace("&#39 ;","")它字面上搜索字符串中的"&#39 ;"事件。你需要将"&#39 ;"转换为它的等同物。试试这个:

s = "That's how we 'roll"
r = s.replace(chr(int('&#39'[2:])), "")

和这个chr(int('&#39'[2:]))你会得到'角色。

Output:

Thats how we roll

注意如果您尝试运行此s.replace(chr(int('&#39'[2:])), "")而不将结果保存在变量中,则原始string不会受到影响。

© www.soinside.com 2019 - 2024. All rights reserved.