在字符串中添加空格

时间:2011-04-18 00:13:03

标签: python string

如何在Python中添加空格?

实施例

print "How many times did " + name + "go here?";

将打印:

How many times didnamego here?"

如何在?

中添加该空格

4 个答案:

答案 0 :(得分:12)

print "How many times did " + name + " go here?"

print "How many times did", name, "go here?"

print "How many times did %s go here?" % name

这个简单案例中的首选形式是第二个。第一个使用连接(如果你想在部分之间多于或少于一个空格,这很有用),第二个使用逗号运算符,它在print的上下文中用空格连接字符串,第三个使用字符串格式(旧的)如果你来自C,Perl,PHP等,它应该看起来很熟悉。第三种是最强大的形式,但在这种简单的情况下,不需要使用格式字符串。

请注意,在Python中,行不需要(也不应该)以分号结束。您还可以使用某些string justification methods在字符串的任一侧或两侧添加多个空格。

答案 1 :(得分:6)

@yookd:欢迎来到SO。这不是一个真正的答案,只是一些提出更好问题的建议。

请在发布前检查您输入的内容。您的print语句不会打印您的说法。 实际上它不会打印任何内容,因为它有语法错误。

>>> name = "Foo"
>>> print "How many times did " + name "go here?";
  File "<stdin>", line 1
    print "How many times did " + name "go here?";
                                                ^
SyntaxError: invalid syntax

+之后您错过了name

>>> print "How many times did " + name + "go here?";
How many times did Foogo here?

即使修复了语法错误,它也没有按照你的说法做到。它所做的是展示获取空间的方法之一(包括它在常量文本中)。

提示:要保存检查,请在Python交互式提示符下输入您的代码,然后将代码和结果直接复制/粘贴到您的问题中,就像我在“回答”中所做的那样。

答案 2 :(得分:1)

print "How many times did ", name, "go here?"

>>> name = 'Some Name'
>>> print "How many times did", name, "go here?"
How many times did Some Name go here?
>>> 

答案 3 :(得分:1)

使用Python 3,

使用打印连接:

>>> name = 'Sue'
>>> print('How many times did', name, 'go here')
How many times did Sue go here

使用字符串连接:

>>> name = 'Sue'
>>> print('How many times did ' + name + ' go here')
How many times did Sue go here

使用格式:

>>> sentence = 'How many times did {name} go here'
>>> print(sentence.format(name='Sue'))
How many times did Sue go here

使用%:

>>> name = 'Sue'
>>> print('How many times did %s go here' % name)
How many times did Sue go here
相关问题