关于python:如何在逗号后不打印空格

How to not print a space after a comma

本问题已经有最佳答案,请猛点这里访问。

这是我当前的代码。 印刷品将在"!"之前放置一个空格。 我在论坛上搜索了一个小时,但现在一切对我来说都太复杂了。 这是一个愚蠢的问题,但我必须知道为什么在逗号后添加此随机空间。

1
2
3
fn = input("What's your First Name?")
ln = input("What's your Last Name?")
print ('Hello,',fn, ln,'!')

>
</p>
<hr>
<p>
在python 3.6中,您可以使用<wyn>f</wyn>字符串,该字符串易于阅读,并且比其他格式方法要快一些:
</p>
<div class=

1
print(f'Hello {fn} {ln}!')

这是格式字符串的工作。

Python 3:

1
print('Hello {} {}!'.format(fn, ln))

Python 2:

1
print 'Hello %s %s!' % (fn, ln)


It's a stupid question, but I have to know why it's adding this random
space after a comma.

打印的默认设置是逗号在其后添加空格。

一种在!之前删除空间的方法是:

1
2
3
4
print('Hello,',fn, ln, end='')
print('!')

Out : Hello, First Last!

在这里,end=指定应在print()语句结束时打印的内容,而不是default newline

另一个简单得多的方法是仅concatenate字符串。即

1
print('Hello,',fn, ln + '!')

您可以将元素放在感叹号(ln)之前,并将'!'连接到末尾:

1
2
3
fn = input("What's your First Name?")
ln = input("What's your Last Name?")
print ('Hello,', fn, ln + '!')

赠送:

1
Hello, Fist Last!

print()语句文档指出:

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep

并且由于默认情况下sep是空格(' '),因此您在传递到function的每个参数之间都留有空格。如上所述,如果您自己将感叹号连接到ln上,则不会插入默认的sep参数,并且不会获得空格。


当您打印字符串列表时,python会插入一个空格。

1
2
3
4
5
6
7
8
$ python3
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 08:49:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type"help","copyright","credits" or"license" for more information.
>>> print('My','name','is','doug')
My name is doug
>>> print('My'+'name'+'is'+'doug')
Mynameisdoug

您想将元素组合成单个字符串,或者(更好的方法)使用字符串格式输出。

1
2
3
4
5
6
7
8
9
>>> fn ="Bob"
>>> ln ="Jones"
>>> msg ="Hello,"+fn+""+ln+"!"
>>> print(msg)
Hello, Bob Jones!
>>> msg ="Hello, {0} {1}!".format(fn,ln)
>>> print(msg)
Hello, Bob Jones!
>>>