尝试在打印语句中用%替换普通var

时间:2018-11-03 09:23:33

标签: python python-3.x variables printing

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

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

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

除了其他代码,还尝试了以下方法: print(%s + ' ' + (input('Enter a number to print')) %(var)),但在%s上给出了语法错误

2 个答案:

答案 0 :(得分:1)

也许您的意思是这样的:

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

%s放在引号内,指示要在字符串中插入的元素的位置。

答案 1 :(得分:1)

不要。这种格式化字符串的方法来自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语句输出-为什么将它们放入然后是同一行?

更好:

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