打印格式化的元组值

时间:2016-05-16 02:16:31

标签: python string list tuples

这可能是最简单的问题。但我尝试以下列方式打印元组的各个值。

mytuple=('new','lets python','python 2.7')

>>> print "%{0} experience, %{1} with %{2} " %mytuple
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    print "%{0} experience, %{1} with %{2} " %mytuple
ValueError: unsupported format character '{' (0x7b) at index 1

我想打印输出如下所示。

"new experience, lets python with python 2.7"

我不记得它在哪里完成。它是否称为解包元组值,打印格式化元组。

6 个答案:

答案 0 :(得分:5)

不要混合printf - 样式格式化和str.format,而是选择一个:

printf-style formatting

>>> mytuple = ('new','lets python','python 2.7')
>>> print "%s experience, %s with %s" % mytuple
new experience, lets python with python 2.7

str.format

>>> print "{0} experience, {1} with {2}".format(*mytuple)
new experience, lets python with python 2.7

答案 1 :(得分:1)

您可以使用格式方法和星号来解决问题。

有关详细信息,请参阅this link

CREATE
OR REPLACE VIEW user_company_view AS
select user_id,  
       company_id  
from   (  
        select     u.id as user_id,  
                   c.id as company_id,  
                   c.parent_company_id,  
                   u.company_id as user_company_id  
        from       user_info u,  
                   company c  
        order by   1, 2 desc  
        limit      10000000000000000000 
       ) base  
where  company_id in (user_company_id, @p) 
and    if(@p := parent_company_id, 1, 1)  

答案 2 :(得分:1)

你可以使用任何一种方法。然而,格式更简单,您可以更轻松地管理它。

>>> a = '{0} HI {1}, Wassup {2}'
>>> a.format('a', 'b', 'c')
'a HI b, Wassup c'
>>> b = ('a' , 'f', 'g')
>>> a.format(*b)
'a HI f, Wassup g'

答案 3 :(得分:1)

你刚刚混淆了printfstr.format,你需要选择其中一个:

>>> tuple1 = ("hello", "world", "helloworld")
>>> print("%s, %s, %s" % tuple1)

或:

>>> tuple1 = ("hello", "world", "helloworld")
>>> print("{}, {}, {}".format(*tuple1))

答案 4 :(得分:0)

只需稍微修改一下:

>>> mytuple=('new','lets python','python 2.7')
>>> print "%s experience, %s with %s " %mytuple
new experience, lets python with python 2.7 
>>> 

答案 5 :(得分:0)

我遇到了元组格式的问题,并找到了解决方案:

  
    
      

mydate =(9,1)       print(“日期为({date [0]},{date [1]})”。format(date = mydate))       日期是(9,1)

    
  

(似乎解决方案仅针对某些问题,使用我们知道的固定元组。)