My code looks like this:
name = Joe
print "Hello", name, "!"
My output looks like:
Hello Joe !
How do I remove the space between Joe and !?
There are several ways of constructing strings in python. My favorite used to be the format function:
print "Hello {}!".format(name)
You can also concatenate strings using the + operator.
print "Hello " + name + "!"
More information about the format function (and strings in general) can be found here:
https://docs.python.org/2/library/string.html#string.Formatter.format
6 Years Later...
You can now use something called f-Strings if you're using python 3.6 or newer. Just prefix the string with the letter f then insert variable names inside some brackets.
print(f"Hello {name}")
a comma after print will add a blank space.
What you need to do is concatenate the string you want to print; this can be done like this:
name = 'Joe'
print 'Hello ' + name + '!'
Joe must be put between quotes to define it as a string.
>>> print (name)
Joe
>>> print('Hello ', name, '!')
Hello Joe !
>>> print('Hello ', name, '!', sep='')
Hello Joe!
You can also use printf style formatting:
>>> name = 'Joe'
>>> print 'Hello %s !' % name
Hello Joe !
One other solution would be to use the following:
Print 'Hello {} !'.format(name.trim())
This removes all the leading and trailing spaces and special character.
Related
This question already has answers here:
Difference between using commas, concatenation, and string formatters in Python
(2 answers)
Closed 2 months ago.
What is the difference between these two pieces of code?
name = input("What is your name?")
print("Hello " + name)
name = input("What is your name?")
print("Hello ", name)
I'm sorry if this question seems stupid; I've tried looking on Google but couldn't find an answer that quite answered my question.
In this example, you have to add an extra whitespace after Hello.
name = input("What is your name?")
print("Hello " + name)
In this example, you don't have to add an extra whitespace (remove it). Python automatically adds a whitespace when you use comma here.
name = input("What is your name?")
print("Hello ", name)
print('a'+'b')
Result: ab
The above code performs string concatenation. No space!
print('a','b')
Result: a b
The above code combines strings for output. By separating strings by comma, print() will output each string separated by a space by default.
According to the print documentation:
print(*objects, sep=' ', end='\n', file=None, flush=False)
Print objects to the text stream file, separated by sep and followed by end.
The default separator between *objects (the arguments) is a space.
For string concatenation, strings act like a list of characters. Adding two lists together just puts the second list after the first list.
print() function definiton is here: docs
print(*objects, sep=' ', end='\n', file=None, flush=False)
Better to explain everything via code
name = "json singh"
# All non-keyword arguments are converted to strings like str() does
# and written to the stream, separated by sep (which is ' ' by default)
# These are separated as two separated inputs joined by `sep`
print("Hello", name)
# Output: Hello json singh
# When `sep` is specified like below
print("Hello", name , sep=',')
# Output: Hello,json singh
# However the function below evaluates the output before printing it
print("Hello" + name)
# Output: Hellojson singh
# Which is similar to:
output = "Hello" + name
print(output)
# Output: Hellojson singh
# Bonus: it'll evaluate the input so the result will be 5
print(2 + 3)
# Output: 5
I am using Python 2.x, and trying to understand the logic of string formatting using named arguments. I understand:
"{} and {}".format(10, 20) prints '10 and 20'.
In like manner '{name} and {state}'.format(name='X', state='Y') prints X and Y
But why this isn't working?
my_string = "Hi! My name is {name}. I live in {state}"
my_string.format(name='Xi', state='Xo')
print(my_string)
It prints "Hi! My name is {name}. I live in {state}"
format doesn't alter the string you call it on; it returns a new string. If you do
my_string = "Hi! My name is {name}. I live in {state}"
new_string = my_string.format(name='Xi', state='Xo')
print(new_string)
then you should see the expected result.
I want to split string that I have.
Lets say string is hello how are you.
I want to print only the how are (meaning start after hello and finish after are
My code for now just start after the hello, but print all the rest.
Want to avoid the you.
ReadJSONFile=JSONResponseFile.read() # this is the txt file with the line
print ReadJSONFile.split('hellow',1)[1] # this gives me everything after hello
You could use string slicing:
>>> s = "hello how are you"
>>> s[6:13]
'how are'
Combine two str.split calls:
>>> s = 'hello how are you'
>>> s.split('hello', 1)[-1]
' how are you'
>>> s.split('hello', 1)[-1].split('you', 1)[0]
' how are '
>>> s.split('hello', 1)[-1].split('you', 1)[0].strip() # remove surrounding spaces
'how are'
If you have the start and end indices you can extract an slice of the string by using the slice notation:
str = 'Hello how are you"
# you want from index 6 (h) to 12 (e)
print str[6:12+1]
This should help: (Using index and slicing)
>>> start = h.index('hello')+len('hello')
>>> end =h.index('you')
>>> h[start:end].strip()
'how are'
Does Python have a function to neatly build a string that looks like this:
Bob 100 Employee Hourly
Without building a string like this:
EmployeeName + ' ' + EmployeeNumber + ' ' + UserType + ' ' + SalaryType
The function I'm looking for might be called a StringBuilder, and look something like this:
stringbuilder(%s,%s,%s,%s, EmployeeName, EmployeeNumber, UserType, SalaryType, \n)
Normally you would be looking for str.join. It takes an argument of an iterable containing what you want to chain together and applies it to a separator:
>>> ' '.join((EmployeeName, str(EmployeeNumber), UserType, SalaryType))
'Bob 100 Employee Hourly'
However, seeing as you know exactly what parts the string will be composed of, and not all of the parts are native strings, you are probably better of using format:
>>> '{0} {1} {2} {3}'.format(EmployeeName, str(EmployeeNumber), UserType, SalaryType)
'Bob 100 Employee Hourly'
Your question is about Python 2.7, but it is worth note that from Python 3.6 onward we can use f-strings:
place = 'world'
f'hallo {place}'
'hallo world'
This f prefix, called a formatted string literal or f-string, is described in the documentation on lexical analysis
You have two options here:
Use the string .join() method: " ".join(["This", "is", "a", "test"])
Use the percent operator to replace parts of a string: "%s, %s!" % ("Hello", "world")
As EmployeeNumber is a int object , or may you have may int amount your variables you can use str function to convert them to string for refuse of TypeError !
>>> ' '.join(map(str,[EmployeeName, EmployeeNumber,UserType , SalaryType]))
'Bob 100 Employee Hourly'
Python has two simple ways of constructing strings:
string formatting as explained here: https://docs.python.org/2/library/string.html
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
and the old style % operator
https://docs.python.org/2.7/library/stdtypes.html#string-formatting
>>> print '%(language)s has %(number)03d quote types.' % \
... {"language": "Python", "number": 2}
Python has 002 quote types.
In C++, \n is used, but what do I use in Python?
I don't want to have to use:
print (" ").
This doesn't seem very elegant.
Any help will be greatly appreciated!
Here's a short answer
x=' '
This will print one white space
print(x)
This will print 10 white spaces
print(10*x)
Print 10 whites spaces between Hello and World
print(f"Hello{x*10}World")
If you need to separate certain elements with spaces you could do something like
print "hello", "there"
Notice the comma between "hello" and "there".
If you want to print a new line (i.e. \n) you could just use print without any arguments.
A lone print will output a newline.
print
In 3.x print is a function, therefore:
print()
print("hello" + ' '*50 + "world")
Any of the following will work:
print 'Hello\nWorld'
print 'Hello'
print 'World'
Additionally, if you want to print a blank line (not make a new line), print or print() will work.
First and foremost, for newlines, the simplest thing to do is have separate print statements, like this:
print("Hello")
print("World.")
#the parentheses allow it to work in Python 2, or 3.
To have a line break, and still only one print statement, simply use the "\n" within, as follows:
print("Hello\nWorld.")
Below, I explain spaces, instead of line breaks...
I see allot of people here using the + notation, which personally, I find ugly.
Example of what I find ugly:
x=' ';
print("Hello"+10*x+"world");
The example above is currently, as I type this the top up-voted answer. The programmer is obviously coming into Python from PHP as the ";" syntax at the end of every line, well simple isn't needed. The only reason it doesn't through an error in Python is because semicolons CAN be used in Python, really should only be used when you are trying to place two lines on one, for aesthetic reasons. You shouldn't place these at the end of every line in Python, as it only increases file-size.
Personally, I prefer to use %s notation. In Python 2.7, which I prefer, you don't need the parentheses, "(" and ")". However, you should include them anyways, so your script won't through errors, in Python 3.x, and will run in either.
Let's say you wanted your space to be 8 spaces,
So what I would do would be the following in Python > 3.x
print("Hello", "World.", sep=' '*8, end="\n")
# you don't need to specify end, if you don't want to, but I wanted you to know it was also an option
#if you wanted to have an 8 space prefix, and did not wish to use tabs for some reason, you could do the following.
print("%sHello World." % (' '*8))
The above method will work in Python 2.x as well, but you cannot add the "sep" and "end" arguments, those have to be done manually in Python < 3.
Therefore, to have an 8 space prefix, with a 4 space separator, the syntax which would work in Python 2, or 3 would be:
print("%sHello%sWorld." % (' '*8, ' '*4))
I hope this helps.
P.S. You also could do the following.
>>> prefix=' '*8
>>> sep=' '*2
>>> print("%sHello%sWorld." % (prefix, sep))
Hello World.
rjust() and ljust()
test_string = "HelloWorld"
test_string.rjust(20)
' HelloWorld'
test_string.ljust(20)
'HelloWorld '
Space char is hexadecimal 0x20, decimal 32 and octal \040.
>>> SPACE = 0x20
>>> a = chr(SPACE)
>>> type(a)
<class 'str'>
>>> print(f"'{a}'")
' '
Tryprint
Example:
print "Hello World!"
print
print "Hi!"
Hope this works!:)
this is how to print whitespaces in python.
import string
string.whitespace
'\t\n\x0b\x0c\r '
i.e .
print "hello world"
print "Hello%sworld"%' '
print "hello", "world"
print "Hello "+"world
Sometimes, pprint() in pprint module works wonder, especially for dict variables.
simply assign a variable to () or " ", then when needed type
print(x, x, x, Hello World, x)
or something like that.
Hope this is a little less complicated:)
To print any amount of lines between printed text use:
print("Hello" + '\n' *insert number of whitespace lines+ "World!")
'\n' can be used to make whitespace, multiplied, it will make multiple whitespace lines.
In Python2 there's this.
def Space(j):
i = 0
while i<=j:
print " ",
i+=1
And to use it, the syntax would be:
Space(4);print("Hello world")
I haven't converted it to Python3 yet.
A lot of users gave you answers, but you haven't marked any as an answer.
You add an empty line with print().
You can force a new line inside your string with '\n' like in print('This is one line\nAnd this is another'), therefore you can print 10 empty lines with print('\n'*10)
You can add 50 spaces inside a sting by replicating a one-space string 50 times, you can do that with multiplication 'Before' + ' '*50 + 'after 50 spaces!'
You can pad strings to the left or right, with spaces or a specific character, for that you can use .ljust() or .rjust() for example, you can have 'Hi' and 'Carmen' on new lines, padded with spaces to the left and justified to the right with 'Hi'.rjust(10) + '\n' + 'Carmen'.rjust(10)
I believe these should answer your question.