【问题标题】:Why isn't my %s format specifier not catching in this snippet?为什么我的 %s 格式说明符没有出现在这个片段中?
【发布时间】:2013-03-23 17:25:49
【问题描述】:
mconfigQuantity = int(raw_input('Enter the number of (m)achine-configurations that you will need: '))
numberOfmconfig = 1


for mconfigs in range(1,mconfigQuantity+1):
    # %s conditional for mcidentifier
    STRINGnumberOfmconfig = str(numberOfmconfig)
    if STRINGnumberOfmconfig[-1] == '1':
        suffix = 'st'
    elif STRINGnumberOfmconfig[-1] == '2':
        suffix = 'nd'
    elif STRINGnumberOfmconfig[-1] == '3':
        suffix = 'rd'
    else: suffix = 'th'
    finalConfigName = STRINGnumberOfmconfig + suffix
    mcidentifier = raw_input('Enter the letter of your %s (m)achine-configuration: ') % (finalConfigName)
    numberOfmconfig = numberOfmconfig + 1






print mconfig()

我已经多次编写并重写了这个 sn-p,但我无法理解为什么它打印 '%s' 而不是用我为它指定的数据替换它。我找不到任何表明它为什么不起作用的东西。

【问题讨论】:

    标签: python format-specifiers


    【解决方案1】:

    应该是

    mcidentifier = raw_input(
        'Enter the letter of your %s (m)achine-configuration: ' % finalConfigName)
    

    您关闭了% 运算符之前的括号,以便将其应用于结果字符串,即raw_input 返回的字符串。

    另请注意,在新代码中建议使用新的字符串格式化语法:

    mcidentifier = raw_input(
     'Enter the letter of your {} (m)achine-configuration: '.format(finalConfigName))
    

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      相关资源
      最近更新 更多