我正在尝试构建一个非常简单的代码SQL代码格式化程序,它从JSON对象中提取查询,目标是将最终输出复制到剪贴板。我还没有进入剪贴板部分,因为我无法使用Python来解释转义字符。
print
函数用转义符和所有字符打印整个东西,我不知道为什么。
import json
main_query = {"text": "SELECTn * from test where id = 1n LIMIT 10"}
query = str(json.dumps(main_query['text']).strip('"'))
print(query) # Not working
print('{}'.format(query)) # Not working either
"""
Output:
SELECTn * from test where id = 1n LIMIT 10
SELECTn * from test where id = 1n LIMIT 10
"""
了解为什么会发生这种情况也很重要。
当您对字符串执行json.dumps((时,您将获得字符串的表示。
例如,如果您执行print(repr(main_query["text]))
,您将得到以下输出:
SELECT n * from test where id = 1 n LIMIT 10
但是,不需要在具有换行符的字符串上执行rep((或json.dumps,并且您希望这些换行符按原样打印。
如果你只做:
import json
main_query = {"text": "SELECT n * from test where id = 1 n LIMIT 10"}
query = main_query['text'].strip('"')
print(query)
你会得到你想要的字符串:
SELECT
* from test where id = 1
LIMIT 10
试试这个:
main_query = {"text": "SELECTn * from test where id = 1n LIMIT 10"}
print(main_query["text"])
SELECT
* from test where id = 1
LIMIT 10
import json
import re
main_query = {"text": "SELECTn * from test where id = 1n LIMIT 10"}
query = main_query['text']
print(re.sub('n',' ',query))
使用此好友、列表和循环打印实现
import json
main_query = {"text": "SELECTn * from test where id = 1n LIMIT 10"}
query = str(json.dumps(main_query['text']).strip('"'))
for word in query.split('\n'):
print(word)