【问题标题】:cleaning a string from escape character with python用python从转义字符中清除字符串
【发布时间】:2013-01-30 15:05:44
【问题描述】:

我从 web 应用程序获取 JSON 格式的数据,其中包括各种 python 转义字符,包括“\n”和“\r”

在将数据输入 sql 之前,我构建了一个小函数来清除有问题的字符和空格中的数据。 (有问题的字符对使用 sql 的另一个应用程序有问题)。

当前函数是:

bad_tokens = [",",";",".","!","'",".","-",'"',"@",r"\n",r"\r"]

from types import StringType, UnicodeType

def sql_text(sqltext, trim = None):
    '''
    helper function to clean text inserted to sql from Priority problematic characters specified bad_tokens

    '''
    thistype = type(sqltext)
    if thistype not in (StringType, UnicodeType):
        return sqltext

    sqltext = sqltext.strip() #priority can't handle string starting with space
    for token in bad_tokens:
        sqltext = sqltext.replace(token,"")
    sqltext = " ".join([i for i in sqltext.split(" ") if i != ""]) #priority can't handle string containing double spaces

    if trim:
        sqltext = sqltext[0:trim]
    return sqltext

这种方法适用于常规字符,但似乎无法清除 \n 和 \r 转义符号。将 r (作为原始字符串)添加到转义符号也无济于事。

感谢您的帮助

编辑:我使用的是 orm (sqlalchemy),所以我不直接访问 DBApi,虽然 sqlalchemy 会自动进行很多转义,因为 sql 将这些字符视为合法,所以 sqlalchemy .回到正题 - 我需要正确清理字符串。

【问题讨论】:

  • 为什么不使用数据库客户端库的 sql 参数功能呢?你在这里重新发明轮子。见wiki.python.org/moin/DbApiFaq
  • ...或查看this问题
  • @MartijnPieters 我已经在使用 sqlalchemy 但是 \r 和 \n 并没有被它转义,至少我可以从结果中看出
  • @alonisser:SQLAlchemy 会转义需要转义的一切,当然包括\r\n。我想你在这里叫错树了。
  • @MartijnPieters 我的问题是 sqlalchemy 不会清理本身不会打扰 sql 的东西,但是使用 mssql 服务器的其他程序(不是我的,.net,无法修复它)是被他们打扰了,尤其是其中一个文本字段中的 \n 让它发疯了..

标签: python string python-2.7 sqlalchemy


【解决方案1】:
import re

newbuff = re.sub("\n|\r| |moreoptions","",yourbuff)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多