我正在尝试执行一个简单的查询,稍后我会将其写入 docx。 查询如下所示:
db_con = DB_CONNECTION()
with db_con.cursor() as cursor:
cursor.execute("Select " + column + " \
FROM table.example \
WHERE code = '" + requirement +"' AND " + column + " != '';")
rows = []
for row in cursor.fetchall():
rows.append(str(row)[2:-4])
return rows
在这种情况下,返回的所有行都是已收集的注释。其中一些包含换行符。
在数据库中,换行符保存为 "\n"
。使用 pyodbc 获取它们会导致它们返回为 "\\n"
,在某些情况下为 "\\\\n"
。 (即使对于同一行,也可以在这两个选项之间进行更改)
有谁知道pyodbc为什么这样做?或者我怎样才能避免这种情况?
我丑陋的解决方案是编写一个函数,它搜索 "\\"
,如果找到 -> 搜索更多相邻的反斜杠并将它们全部替换为一个。
感谢您的帮助!
答案 0 :(得分:0)
您对 Python 对包含反斜杠的字符串的表示感到困惑。
>>> backsl = chr(0x5c) # string containing a single backslash
>>> hello = "Hello" + backsl + "n" + "world!"
>>> # printing the string looks normal
>>> print(hello)
Hello\nworld!
>>> the default string *representation* doubles up the backslash
>>> hello
'Hello\\nworld!'
>>> str(hello)
'Hello\\nworld!'
# if you call `repr()` and then print() or str() that then the backslashes get doubled again
>>> rep = repr(hello)
>>> print(rep)
'Hello\\nworld!'
>>> rep
"'Hello\\\\nworld!'"
>>> str(rep)
"'Hello\\\\nworld!'"
请注意,仅将值转储到控制台(例如,>>> hello
)会对其进行隐式 str()
。