Python中MySQL语句, 遇到同时有单引号, 双引号处理方式 !r, repr()

SQL语句:

insert_cmd = "INSERT INTO {0} SET {1}"
.format(db_conn.firmware_info_table, 
    ','.join(['{0}={1!r}'.format(k, str(v)) for (k, v) in info_dict.items()]))

{0}={1!r} 作用是设置字段的值,一般情况应该是:

{0}='{1}'.format(columnA, value)

但若value中同时有双引号和单引号("", ''), 则会在execute(insert_cmd)时报错,所以需要使用!r来调用repr() 函数, 将对象转化为供解释器读取的形式。
repr() 返回一个对象的 string 格式。
!r 表示使用repr()替代默认的str()来返回。

According to the Python 2.7.12 documentation:
!s (apply str()) and !r (apply repr()) can be used to convert the value before it is formatted.

贴出str类中的repr说明:

repr(object)
Return a string containing a printable representation of an object.
This is the same value yielded by conversions(reverse quotes).
It is sometimes useful to be able to access this operation as an ordinary function.
For many types, this function makes an attempt to return a string that would yield
an object with the same value when passed to eval(),
otherwise the representation is a string enclosed in angle brackets
that contains the name of the type of the object together with additional information
often including the name and address of the object. A class can control what this function
returns for its instances by defining a __repr__() method.

猜你喜欢

转载自blog.csdn.net/tmaccs/article/details/82559207