试图用打印状态中的%替换普通变量

2024-04-25 20:35:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

现在,我正在尝试打印变量的输出以及使用%方法表示“youhaveentered”的字符串。你知道吗

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


Tags: to方法字符串代码numberinputvarprint
2条回答

不要这样做。这种格式化字符串的方法来自Python2.x,在Python3.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)。它有几个选项来控制输出-例如,如果给定多个对象,使用什么作为分隔符:

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

也许你的意思是这样的:

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

%s位于引号内,指示要插入字符串的元素的位置。你知道吗

相关问题 更多 >