Add a space in string
How can I add a blank space in Python?
Ex.
print "How many times did " + name + "go her开发者_运维知识库e?";
will print:
How many times didnamego here?"
How can I add that space in?
print "How many times did " + name + " go here?"
or
print "How many times did", name, "go here?"
or
print "How many times did %s go here?" % name
The preferred form in this simple case is the second one. The first uses concatenation (which is useful if you want more or less than one space between parts), the second uses the comma operator, which in the context of print joins the strings with a space, and the third uses string formatting (the old style), which should look familiar if you come from C, Perl, PHP, etc. The third is the most powerful form, but in this simple cases the use of format strings is unnecessary.
Note that in Python, lines do not need to be (and should not be) ended by semicolons. You can also use some of the string justification methods to add several spaces on either or both sides of the string.
@yookd: Welcome to SO. This is not a real answer, just some suggestions for asking better questions.
Please check what you have typed before posting. Your print
statement does not print what you say it does. In fact it doesn't print anything, because it has a syntax error.
>>> 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
You are missing a +
after name
:
>>> print "How many times did " + name + "go here?";
How many times did Foogo here?
And even after fixing the syntax error it doesn't do what you said it does. What it does do is demonstrate one of the ways of getting a space (including it in the constant text).
Hint: To save checking, enter your code at the Python interactive prompt and then copy/paste the code and the results straight into your question, just as I did in this "answer".
With Python 3,
Using print concatenation:
>>> name = 'Sue'
>>> print('How many times did', name, 'go here')
How many times did Sue go here
using string concatenation:
>>> name = 'Sue'
>>> print('How many times did ' + name + ' go here')
How many times did Sue go here
using format:
>>> sentence = 'How many times did {name} go here'
>>> print(sentence.format(name='Sue'))
How many times did Sue go here
using %:
>>> name = 'Sue'
>>> print('How many times did %s go here' % name)
How many times did Sue go here
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?
>>>
精彩评论