在python 3中没有空格打印 [英] Print without space in python 3

查看:52
本文介绍了在python 3中没有空格打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我想知道如何打印多个值而不在中间添加额外的空间.我想要输出 ab 而不是 a b 而不必调用 print 两次:

print("a", end="")打印(b")

另外,我有以下代码:

a = 42乙 = 84

并且我想将它们的值打印为 a = 42, b = 84,但如果我这样做

print("a = ", a, ", ", b = ", b)

添加额外的空格(它输出 a = 42 , b = 84)

而 Java 风格,

print("a = " + a + ", b = " + b)

引发 TypeError.

解决方案

你可以使用 sep 参数去掉空格:

<预><代码>>>>打印(a",b",c")a b c>>>打印(a",b",c",sep =")美国广播公司

我不知道你说的Java 风格"是什么意思;在 Python 中,您不能以这种方式将字符串添加到(比如说)整数中,尽管如果 ab 是字符串,它会起作用.当然,您还有其他几种选择:

<预><代码>>>>打印("a = ", a, ", b = ", b, sep="")a = 2, b = 3>>>打印("a = " + str(a) + ", b = " + str(b))a = 2, b = 3>>>print("a = {}, b = {}".format(a,b))a = 2, b = 3>>>打印(fa = {a},b = {b}")a = 2, b = 3

最后一个需要 Python 3.6 或更高版本.对于早期版本,您可以模拟相同的效果(虽然我一般不推荐这样做,但有时它会派上用场,否则假装也没意义):

<预><代码>>>>print("a = {a}, b = {b}".format(**locals()))a = 2, b = 3>>>print("b = {b}, a = {a}".format(**locals()))b = 3,a = 2

I'm new to Python, and I'm wondering how to print multiple values without having the extra space added in between. I want the output ab rather than a b without having to call print twice:

print("a", end="")
print("b")

Also, I have the following code:

a = 42
b = 84 

and I want to print their values as a = 42, b = 84, yet if I do

print("a = ", a, ", ", b = ", b)

extra spaces are added (it outputs a = 42 , b = 84)

Whereas the Java style,

print("a = " + a + ", b = " + b)

raises a TypeError.

解决方案

You can use the sep parameter to get rid of the spaces:

>>> print("a","b","c")
a b c
>>> print("a","b","c",sep="")
abc

I don't know what you mean by "Java style"; in Python you can't add strings to (say) integers that way, although if a and b are strings it'll work. You have several other options, of course:

>>> print("a = ", a, ", b = ", b, sep="") 
a = 2, b = 3
>>> print("a = " + str(a) + ", b = " + str(b))
a = 2, b = 3
>>> print("a = {}, b = {}".format(a,b))
a = 2, b = 3
>>> print(f"a = {a}, b = {b}")
a = 2, b = 3

The last one requires Python 3.6 or later. For earlier versions, you can simulate the same effect (although I don't recommend this in general, it comes in handy sometimes and there's no point pretending otherwise):

>>> print("a = {a}, b = {b}".format(**locals()))
a = 2, b = 3
>>> print("b = {b}, a = {a}".format(**locals()))
b = 3, a = 2

这篇关于在python 3中没有空格打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆