• Python 序列类型拆包 %s 和'{}'.format 的功能差异之一


    >>> 1, 2, 3 #这样写成一行相当于一个元组
    (1, 2, 3)
    >>> x = 1, 2, 3
    >>> x
    (1, 2, 3)
    >>> type(x)
    <class 'tuple'>
    >>> x, y, z = 4, 6, 5
    >>> x, y, z
    (4, 6, 5)
    >>> tx = x, y, z
    >>> tx
    (4, 6, 5)
    >>> a, b, c = tx
    >>> a
    4
    >>> b
    6
    >>> c
    5
    >>> (1, 3, 5)
    (1, 3, 5)
    >>>

    >>> li = [('张三', 50), ('李四', 30)]
    >>> for name,_ in li:
    ... print(name)
    ... print(_)
    ...
    张三
    50
    李四
    30

    >>> for inf in li:
    ... print('%s__%s' % inf)  #这个功能只有%s 能做到, '{}'.format()做就会出错
    ...
    张三__50
    李四__30
    >>> for inf in li:
    ... print('{}, {}'.format(inf))
    ...
    Traceback (most recent call last):
    File "<stdin>", line 2, in <module>
    IndexError: tuple index out of range
    >>> for inf in li:
    ... print('{}, {}'.format inf)
    File "<stdin>", line 2
    print('{}, {}'.format inf)
    ^
    SyntaxError: invalid syntax

    >>> for inf in li:
    ... print('{}, {}'.format(*inf)) # 如果用*拆包, 就可以了
    ...
    张三, 50
    李四, 30

    '%s'无法拆字符串的包,  但是'{}'.format()却可以:

    >>> st = 'abcd'
    >>> *st
    File "<stdin>", line 1
    SyntaxError: can't use starred expression here
    >>> s, *a = st
    >>> a
    ['b', 'c', 'd']
    >>> s
    'a'
    >>> print('%s %s %s %s' % st)

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: not enough arguments for format string

    >>> print('%s %s %s %s' % (st))
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: not enough arguments for format string

    >>> print('%s %s %s %s' %(*st))
    File "<stdin>", line 1
    SyntaxError: can't use starred expression here


    >>> print('{}'.format(*st))
    a
    >>> print('{2}'.format(*st))
    c
    >>>

    >>> l = (4, 5)
    >>> def jia(x, y):
    ... return x+y
    ...
    >>> jia(*l)
    9
    >>>

  • 相关阅读:
    构建自己的PHP框架--定义ORM的接口
    装X神器--Hacker Typer
    inno setup读取注册表遇到的一个坑
    一个简单的inno setup模板
    Android Studio导入项目非常慢的解决办法
    Android Studio快捷键每日一练(6)
    Android Studio快捷键每日一练(5)
    Android Studio快捷键每日一练(4)
    Android中的FragmentManager的问题
    Android Studio快捷键每日一练(3)
  • 原文地址:https://www.cnblogs.com/guiyuhua/p/8631529.html
Copyright © 2020-2023  润新知