【问题标题】:What does {0} mean in this Python string?这个 Python 字符串中的 {0} 是什么意思?
【发布时间】:2011-07-13 17:09:46
【问题描述】:

以下程序在字符串中使用 {0},我不确定它是如何工作的,它出现在有关 Python 迭代的在线教程中,我似乎找不到任何解释它的地方。

import random

number = random.randint(1, 1000)
guesses = 0

print("I'm thinking of a number between 1 and 1000.")

while True:
   guess = int(input("\nWhat do you think it is? "))
   guesses += 1

    if guess > number:
        print("{0} is too high.".format(guess))
    elif guess < number: 
        print("{0} is too low.".format(guess))
    else:
        break

print("\nCongratulations, you got it in {0} guesses!\n".format(guesses))

谢谢!

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    这是格式方法的一个指标,您希望它被格式的第一个(索引零)参数替换。 (例如"2 + 2 = {0}".format(4)

    【讨论】:

      【解决方案2】:

      多次放置相同的参数是一个福音

      print("When you multiply {0} and {1} or {0} and {2}, the result is {0}".format(0,1,2))
      

      这不是很好吗!!!

      【讨论】:

      • 挺好的,只不过0加1的时候结果是1,不是0;)
      【解决方案3】:

      http://docs.python.org/release/3.1.3/library/stdtypes.html#str.format

      执行字符串格式化操作。 format_string 参数可以 包含由大括号 {} 分隔的文字文本或替换字段。 每个替换字段都包含一个数字索引 位置参数,或关键字参数的名称。返回副本 的 format_string ,其中每个替换字段都替换为 对应参数的字符串值。

      【讨论】:

      • +1 用于链接到 op 似乎找不到的解释。
      • +1 用于链接到顶部答案(投票数的三倍!)没有费心指向的文档。
      【解决方案4】:

      这是一个占位符,将替换为结果中format 的第一个参数。 {1} 将是第二个参数,依此类推。

      详情请见Format String Syntax

      【讨论】:

        【解决方案5】:

        这是新的 python 格式化样式。阅读它here

        【讨论】:

          【解决方案6】:
          year = int(input("Enter the year: "))
          if year%4 == 0:
              if year%100 == 0:
                  if year%400 == 0:
                      print("{0} Year is Leap Year".format(year))
                  else:
                      print("{0} Year is Not Leap Year".format(year))
              else:
                  print("{0} Year is Leap Year".format(year))
          else:
              print("{0} Year is Not Leap Year".format(year))
          

          在这里我可以使用.format(year)year 参数放在多行中

          输出:

          > Enter the year: 1996
          > 1996 Year is Leap Year
          

          AND 另一个例子:

          name = 'sagar'
          place = 'hyd'
          greet = 'Good'
          print("my name is {0}. I am from {1}. Hope everyone doing {2}".format(name,place,greet))
          

          输出:

          > my name is sagar.
          > I am from hyd. Hope everyone doing Good
          

          print("my name is {0}. I am from {1}. Hope everyone doing {2}".format('Sagar','Hyd','Good'))
          

          输出:

          > my name is sagar. I am from hyd. Hope everyone doing Good
          

          【讨论】:

            猜你喜欢
            • 2018-05-01
            • 1970-01-01
            • 2011-12-06
            • 2012-02-20
            • 2022-11-27
            • 1970-01-01
            • 2011-06-10
            • 1970-01-01
            • 2018-01-15
            相关资源
            最近更新 更多