【问题标题】:Trying to replace a normal var with % in a print statement尝试在打印语句中用 % 替换普通 var
【发布时间】:2018-11-03 09:23:33
【问题描述】:

基本上我正在学习一些 python 基础知识,并且执行以下操作没有问题:

print(var1 + ' ' + (input('Enter a number to print')))

现在我正在尝试使用 % 方法打印变量的输出以及说明“您已输入”的字符串。

除了其他代码之外,已经尝试过这个: print(%s + ' ' + (input('Enter a number to print')) %(var)) 但在 %s 上出现语法错误

【问题讨论】:

    标签: python python-3.x variables printing


    【解决方案1】:

    也许你的意思是这样的:

    print('%s %s'%(var1, input('Enter a number to print')))
    

    %s 位于引号内,表示要插入到字符串中的元素的位置。

    【讨论】:

    • 这对我来说是比较基本的理解。小问题,我看到 print('%s'%(var1, input('Enter a number to print'))) 无法编译并出现错误“TypeError:字符串格式化期间并非所有参数都转换”。使用 %s %s 而不是只使用一个 %s 会有什么影响。提前致谢!
    • 使用%s %s,您试图在字符串中插入两个元素。 var1 进入第一个 %s 的位置,input 的结果进入第二个 %s 的位置。
    【解决方案2】:

    不要。这种格式化字符串的方式来自 python 2.x,在 python 3.x 中处理字符串格式化的方式还有很多:


    您的代码有 2 个问题:

    print(var1 + ' ' + (input('Enter a number to print')))
    

    如果var1 是一个字符串,它就可以工作——如果不是,它就会崩溃:

    var1 = 8
    print(var1 + ' ' + (input('Enter a number to print')))
    
    Traceback (most recent call last):
      File "main.py", line 2, in <module>
        print(var1 + ' ' + (input('Enter a number to print')))
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    

    你可以这样做

    var1 = 8
    print(var1 , ' ' + (input('Enter a number to print')))
    

    但是你失去了格式化var1的能力。另外:inputprint 之前被评估,所以它的文本在一行,然后是print-statements 输出 - 为什么把它们放在同一行呢? p>

    更好:

    var1 = 8
    
    # this will anyhow be printed in its own line before anyway
    inp = input('Enter a number to print')
    
    # named formatting (you provide the data to format as tuples that you reference
    # in the {reference:formattingparams}
    print("{myvar:>08n} *{myInp:^12s}*".format(myvar=var1,myInp=inp))
    
    # positional formatting - {} are filled in same order as given to .format()
    print("{:>08n} *{:^12s}*".format(var1,inp))
    
    # f-string 
    print(f"{var1:>08n} *{inp:^12s}*")
    
    # showcase right align w/o leading 0 that make it obsolete
    print(f"{var1:>8n} *{inp:^12s}*")
    

    输出:

    00000008 *   'cool'   *
    00000008 *   'cool'   *
    00000008 *   'cool'   *
           8 *   'cool'   *
    

    迷你格式参数的意思是:

    :>08n    right align, fill with 0 to 8 digits (which makes the > kinda obsolete)
             and n its a number to format
    
    :^12s    center in 12 characters, its a string
    

    也请查看print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)。它有几个选项来控制输出 - f.e.如果给出多个东西,用什么作为分隔符:

    print(1,2,3,4,sep="--=--") 
    print(  *[1,2,3,4], sep="\n")  # *[...] provides the list elemes as single params to print
    

    输出:

    1--=--2--=--3--=--4
    
    1
    2
    3
    4
    

    【讨论】:

    • 工作得很好,有点高级,但很快就会到达那里:D 非常感谢您的时间!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 2014-02-12
    相关资源
    最近更新 更多