推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
terence4444
V2EX  ›  Python

[Python 语法] 询问在 String 中关于 % 的用法(找不到相关文档)

  •  
  •   terence4444 · Jan 25, 2016 · 4858 views
    This topic created in 3794 days ago, the information mentioned may be changed or developed.
    请问以下的用法相关文档可以在哪里找到?我想知道是否关于 % 还有其它用法。

    string1 = 'string replace %s'
    string2 = 'abcdefg'
    string3 = string1 % string2
    >> string3 == 'string replace abcdefg'

    谢谢
    Supplement 1  ·  Feb 14, 2016
    很抱歉这帖过了这么久才来总结:

    感谢 @zk8802 找到的文档
    https://docs.python.org/2/library/stdtypes.html#string-formatting

    Python 同时支持 % 与 format 替换字符串:
    如(不要使用这种方法写 SQL 容易被注入):
    sql_cause = "replace into tabls(%(fields)s) values(%(values)s) "
    params = {'fields': 'f1,f2,f3', 'values': 'v1,v2,v3'}
    sql_cause = sql_cause % params

    或者(不要使用这种方法写 SQL 容易被注入):
    用 format 应该可以等同为:
    "replace into tabls({0}) values({1}) ".format('f1,f2,f3', 'v1,v2,v3')
    感谢 @ethego @necomancer @qihboy @fy 指出官方推荐使用 format 方法

    根据 @vmebeh 提供的文档:
    https://www.python.org/dev/peps/pep-3101/
    我将 SQL 代码改写成了:
    fieldlist = "f1,f2,f3" #为了动态拼接需要的字段名
    valuelist = "%s,%s,%s"
    param = (v1,v2,v3,)
    sql_cause = "replace into table ({0}) values({1}) ".format(fieldlist, valuelist)
    n = cursor.execute(sql_cause, param)

    以上应该是全部的过程了,如果还有问题,欢迎再次指出。
    36 replies    2016-02-14 18:09:27 +08:00
    terence4444
        2
    terence4444  
    OP
       Jan 25, 2016
    @zk8802 感谢,连页面 tag 都打好了,太贴心 :)
    ethego
        3
    ethego  
       Jan 25, 2016   ❤️ 1
    建议使用 format 方法,%什么的估计只有写 c 的转 python 才会用。"{0}, {1}{2}".format("hello", "world", 1) >>> "hello, world1"
    terence4444
        4
    terence4444  
    OP
       Jan 25, 2016
    @ethego 感谢,我在文档中看到这个写法和 format 写法等同的,我本来要写动态 SQL 用的……

    sql_cause = "replace into tabls(%(fields)s) values(%(values)s) "
    params = {'fields': 'f1,f2,f3', 'values': 'v1,v2,v3'}
    sql_cause = sql_cause % params

    用 format 应该可以等同为(还没测):
    "replace into tabls({0}) values({1}) ".format('f1,f2,f3', 'v1,v2,v3')

    Python 推荐用第二种吗?
    ethego
        5
    ethego  
       Jan 25, 2016   ❤️ 1
    @terence4444 推荐第二种,比第一种更加简洁明了,还不用考虑类型的问题
    ethego
        6
    ethego  
       Jan 25, 2016
    @terence4444 写 sql 拼接字符串,小心 sql 注入
    terence4444
        7
    terence4444  
    OP
       Jan 25, 2016
    @ethego 谢谢提醒
    这个是我自己跑定时任务抓东西用的, field 和 value 都是固定写死的几个字段的排列组合(抓到某个值就写上字段和值,没有抓到的就跳过不更新)
    没有用户输入,应该没有关系吧…… 有用户输入的肯定会 encode 一下的。
    qihboy
        8
    qihboy  
       Jan 25, 2016   ❤️ 1
    % 是 python 的表达式
    .format 是方法,现在推荐用 format 而已
    vmebeh
        9
    vmebeh  
       Jan 25, 2016   ❤️ 1
    拼接 sql 语句不安全,用 ? 占位, tuple 传值


    https://docs.python.org/2/library/sqlite3.html

    ```# Never do this -- insecure!
    symbol = 'RHAT'
    c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

    # Do this instead
    t = ('RHAT',)
    c.execute('SELECT * FROM stocks WHERE symbol=?', t)
    print c.fetchone()
    ```
    fy
        10
    fy  
       Jan 25, 2016
    @qihboy 咦,请问 python 推荐用 format ,有出处吗?
    一直在用 %s 来输出全部类型……
    necomancer
        11
    necomancer  
       Jan 26, 2016 via Android   ❤️ 2
    RqPS6rhmP3Nyn3Tm
        12
    RqPS6rhmP3Nyn3Tm  
       Jan 26, 2016 via iPad
    写了这么久第一次知道还有 format 写法,果然写 C 写习惯了……
    guoqiao
        13
    guoqiao  
       Jan 26, 2016
    @ethego 还可以更简单:

    "{}, {}{}".format("hello", "world", 1) >>> "hello, world1"
    leavic
        14
    leavic  
       Jan 26, 2016
    习惯了 format 写法,我都快忘记%方法怎么写了
    clockwerk
        15
    clockwerk  
       Jan 26, 2016
    习惯了%,不知道耗能 format
    qihboy
        16
    qihboy  
       Jan 26, 2016
    @fy https://docs.python.org/2/library/stdtypes.html#str.format

    This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code.

    New in version 2.6.
    Karblue
        17
    Karblue  
       Jan 26, 2016
    %写法写起来更快 。 format 都懒得敲
    huangfs
        18
    huangfs  
       Jan 26, 2016
    也是习惯%
    TheCure
        19
    TheCure  
       Jan 26, 2016
    这东西叫占位符
    要是你知道这叫占位符,搜起来就很快了
    pynix
        20
    pynix  
       Jan 26, 2016
    字符串插值, format 是 Java 那边搞过来的,有点背道而驰。
    fy
        21
    fy  
       Jan 26, 2016
    @necomancer
    @qihboy

    虽然 PEP3101 并没有推荐不推荐的内容, str.format 的 3.5 版本文档里也没有这句话,但我在别处发现了一段信息:
    https://docs.python.org/3.5/library/stdtypes.html#printf-style-string-formatting

    Note: The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format() interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.

    他说元组和字典的显示有问题,然而貌似并没有:

    >>> '%s and %s a' % ((1,2,3), {1:2, 'a':2})
    "(1, 2, 3) and {1: 2, 'a': 2} a"

    不知道为什么官方文档会有如此明显的倾向性,还没给出合适的例子。我个人觉得 .format 作为一个复杂蛋疼的机制,还是太冗长,不讨喜。
    hitmanx
        23
    hitmanx  
       Jan 26, 2016
    说找不到也是蛮奇怪的事,我 google "python string percentage sign",前 5 条都是关于这个的,其中第 5 条就是官方doc.
    terence4444
        24
    terence4444  
    OP
       Jan 26, 2016
    @hitmanx 我用 "Python String Operator %" 找的…… 以为是一个 operator ,昨天在家用的 Bing
    hitmanx
        25
    hitmanx  
       Jan 26, 2016
    @terence4444 不是我较真啊.按照你的关键词搜,无论是 bing 还是 google 前几个结果都是关于这个的啊,莫非是我这里搜索多了排名有优化?

    bing 的结果如下..除了第二个可能不对以外,其他的每个都包含了 "% operator", "string formatting"之类的关键字.

    7.1. string — Common string operations — Python …
    https://docs.python.org/2/library/string
    The string module contains a number ... Python ’ s built-in string classes support ... To output formatted strings use template strings or the % operator described in ...

    python convert a string to an operator - Stack Overflow
    stackoverflow.com/.../5117112/python-convert-a-string-to-an-operator
    RESOLVEDLAST UPDATED: 2/25/20113 POSTSFIRST POST: 2/25/2011
    Is it possible to convert a string to an operator in python? I would like to pass a condition to a function Ideally it would look like this: def foo(self, attribute ...

    performance - Python string formatting: % vs. .format ...
    stackoverflow.com/questions/5082452
    RESOLVEDLAST UPDATED: 12/23/20138 POSTSFIRST POST: 2/22/2011
    Python 2.6 introduced the str.format() method with a slightly different syntax from the existing % operator. Which is better and for what situations? The following ...

    5. Built-in Types — Python 2.7.11 documentation
    https://docs.python.org/2/library/stdtypes
    To output formatted strings use template strings or the % operator described in the String Formatting Operations section. ... String (converts any Python object using str
    Python Strings - Tutorialspoint

    www.tutorialspoint.com/python/python_strings.htm
    String Formatting Operator. One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having ...
    se77en
        26
    se77en  
       Jan 26, 2016
    最全的解释 https://pyformat.info
    terence4444
        27
    terence4444  
    OP
       Jan 26, 2016
    @hitmanx 我找的结果好像和你贴的不一样,不过即使一样也没有很多相关信息把引导到 format 上去

    7.1. string — Common string operations — …翻译此页
    The string module contains a number ... Python ’ s built-in string classes support ... To output formatted strings use template strings or the % operator described in ...

    python convert a string to an operator - Stack Overflow
    最佳答案 Is it possible to convert a string to an operator in python? I would like to pass a condition to a function Ideally it would look like this: def foo(self, attribute ...详情
    stackoverflow.com/.../5117112/python-convert-a-string-to-an-operator  ·  2011-02-25

    9.9. operator — Standard operators as functions …翻译此页
    This table shows how abstract operations correspond to operator symbols in the Python syntax and the functions in the ... String Formatting: s % obj: mod(s, obj ...

    5. Built-in Types — Python 2.7.11 documentation 翻译此页
    To output formatted strings use template strings or the % operator described in the String Formatting Operations section. ... String (converts any Python object using str

    BitwiseOperators - Python Wiki 翻译此页
    These are Python's bitwise operators. ... they treat it as if it were a string of bits, ... Python allows operator overloading, ...
    https://wiki.python.org/moin/BitwiseOperators
    Operators and String Formatting in Python - …翻译此页
    Operators and String Formatting . Terms in This Chapter . Format directives; Hexdump; Key; Keyword; Literal; Modulus; Operator precedence; Boolean value; Class ...
    www.informit.com/articles/article.aspx?p=28790

    在第一个搜索结果中并没有 format 这样的用法,我都是打开然后直接搜索 % 符号找的,知道 % 和 format 是一样的话应该可以找到,但是不知道的话,我觉得并不是那么容易。
    necomancer
        28
    necomancer  
       Jan 26, 2016 via Android
    @fy

    a = (1, 2)
    print("position is %s" % name) 会报错,需要
    (name, )的写法吧。
    necomancer
        29
    necomancer  
       Jan 26, 2016 via Android
    @fy

    BTW 我个人也倾向 %, 感觉更直白简单一点
    necomancer
        30
    necomancer  
       Jan 26, 2016 via Android
    我了个脑残,变量名都弄错了, V2EX 好像也不能改
    MinskyNg
        31
    MinskyNg  
       Jan 26, 2016
    新版的 python 教程好像都推荐 format,功能更强大
    kkzxak47
        32
    kkzxak47  
       Jan 26, 2016
    format 更简单,开始用就会喜欢上它
    Arthur2e5
        33
    Arthur2e5  
       Jan 26, 2016   ❤️ 1
    @terence4444 第一种 %(foo)s 指定了字段的名称,经常能让东西更可读(特别是翻译软件的时候译者可以直接看到这里是什么东西)——相应地你应该在 format 里面用 "{foo}".format(foo='bar')。

    @ethego 考虑类型…… Python 还 Better Explicit than Implicit 呢。主要是 format 功能性重要啦。
    ming2281
        34
    ming2281  
       Jan 26, 2016 via Android
    楼主用过 ipython 没
    如果没有,推荐试试,大部分问题都会烟消云散
    你这种查帮助文档的问题,在 ipython 里面都不值一提

    它非常强大,强大到它变成了我现在的默认 linux shell
    terence4444
        35
    terence4444  
    OP
       Jan 31, 2016
    @ming2281 这台电脑我还要打游戏……公司里摸鱼写 Python 的电脑也是 Windows 的,所以没有 Linux ……
    terence4444
        36
    terence4444  
    OP
       Feb 14, 2016
    在附言 1 中总结了这帖的内容,应该算是结帖了,撒花。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1187 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 95ms · UTC 17:49 · PVG 01:49 · LAX 10:49 · JFK 13:49
    ♥ Do have faith in what you're doing.