简体   繁体   English

Python 如何在运行时修复语法错误

[英]Python how to fix syntax error during runtime

If I receive a string below with syntax error from a noSQL db that stores it in this exact format, how can I assign it to a variable and "correct" the syntax error during runtime.如果我从以这种确切格式存储它的 noSQL db 收到以下带有语法错误的字符串,我如何将其分配给变量并在运行时“纠正”语法错误。 With assumptions that I cannot change how it is stored on a database.假设我无法更改它在数据库中的存储方式。

Since this is a syntax error I can't even use string functions like replace or regex to remove the extra quotations enclosing the phone number.由于这是一个语法错误,我什至不能使用替换或正则表达式等字符串函数来删除包含电话号码的额外引号。

string = "John Doe "(123) 456-7890"" string = "John Doe "(123) 456-7890""

Desired final result would be for it to not throw a syntax error and compile.期望的最终结果是它不会抛出语法错误并编译。 I'd appreciate any help I can get.我会很感激我能得到的任何帮助。 Thanks.谢谢。

That string assignment indeed throws a SyntaxError if executed as part of your code, but it's not an error for that string to be read from from a database.如果作为代码的一部分执行,该字符串分配确实会引发SyntaxError ,但从数据库中读取该字符串并不是错误。

In which case it works just as if you had single-quoted the string:在这种情况下,它的工作方式就像您单引号中的字符串一样:

string = 'John Doe "(123) 456-7890"'

It works if you escape the internal quotes with '\' or enclose string with single quotes.如果您使用 '\' 转义内部引号或用单引号括住字符串,它会起作用。

string_param = 'John Doe "(123) 456-7890"'.replace('"', '')

if it's multi-line string, you can use this -如果它是多行字符串,您可以使用它 -

string_param = """
'John Doe "(123) 456-7890"'.replace('"', '')
""".replace('"', '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM