为什么字符串中的变量和标点符号之间有一个额外的空格?Python

Des*_*iny 2 python

字符串的输出中有一个额外的空格。这是发生这种情况的代码部分。它发生在函数的字符串 nameConfirmation() 中。

def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    print ("Right... So your name is", name,".")
Run Code Online (Sandbox Code Playgroud)

这是它给出的输出。

Right... So your name is Raven .
Run Code Online (Sandbox Code Playgroud)

如何去掉名字和标点符号之间的空格?

Mer*_*Lee 5

您可以附加字符串+

print ("Right... So your name is", name + ".")
Run Code Online (Sandbox Code Playgroud)

输出:

Right... So your name is Raven.
Run Code Online (Sandbox Code Playgroud)


End*_*ook 5

如果您使用:

print ("Right... So your name is", name,".")
Run Code Online (Sandbox Code Playgroud)

你会注意到输出是:

Right... So your name is Raven .
Run Code Online (Sandbox Code Playgroud)

isnameRaven)。您可以在输出中注意一个空格 ( is Raven),这是因为print()有一个默认参数sep,默认情况下它是print("Right... So your name is", name,".", sep = ' '). 这样的说法是,它在每个绳子与昏迷级联的末端添加了一个串,中的print功能。
因此,如果您这样做print('A','B'),它将是A B,因为当您连接Aand 时Bprint将添加 ' '(和空格)作为胶水。
你可以配置它:print('A','B', sep='glue')会打印AglueB

要解决您的问题,您可以做两个选择。

  • sep = ''在 之后更改并添加一个空格isprint ("Right... So your name is ", name,".", sep='')
  • 或者,使用+最后两个字符串连接:print ("Right... So your name is", name + ".")

还有很多其他的方法,比如:(我根据我的主观意见从最坏到最好对它们进行排序......)

  • print("Right... So your name is %s." % name).
  • print("Right... So your name is {}.".format(name)).
  • print(f"Right... So your name is {name}.")

文档链接:

PS:这不是答案的一部分,只是一个注释。

  • print (something)不需要空间 --> print(something)
  • Futhemorersep = ' '也称为end = '\n'确定打印的结尾(\n= 换行)。

P.S 2: Thanks Ouss for the idea of add some documentations links. I've just learnt that you can do print(%(key)s % mydict)!