如何打印值之间没有空格的变量 [英] How to print variables without spaces between values

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

问题描述

我想知道如何在打印内容时删除额外的空格.

I would like to know how to remove additional spaces when I print something.

就像我做的那样:

print 'Value is "', value, '"'

输出将是:

Value is " 42 "

但我想要:

Value is "42"

有没有办法做到这一点?

Is there any way to do this?

推荐答案

如果您不想要空格,请不要使用 print ...,(带有尾随逗号).使用字符串连接或格式化.

Don't use print ..., (with a trailing comma) if you don't want spaces. Use string concatenation or formatting.

串联:

print 'Value is "' + str(value) + '"'

格式:

print 'Value is "{}"'.format(value)

后者更加灵活,参见str.format() 方法文档格式化字符串语法部分.

The latter is far more flexible, see the str.format() method documentation and the Formatting String Syntax section.

您还会遇到较旧的% 格式样式:

You'll also come across the older % formatting style:

print 'Value is "%d"' % value
print 'Value is "%d", but math.pi is %.2f' % (value, math.pi)

但这不如新的 str.format() 方法灵活.

but this isn't as flexible as the newer str.format() method.

在 Python 3.6 和更新版本中,您将使用格式化字符串 (f-string):

In Python 3.6 and newer, you'd use a formatted string (f-string):

print(f"Value is {value}")

这篇关于如何打印值之间没有空格的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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