I want to create a string, but include comments for each part. In Python, I can do this inside the function print, but I can't do it if I'm creating a variable.
print("Hello " + # WORKS
"World!")
greeting = "Hello " + # FAILS
"World!"
print(greeting)
Throws the error:
File "space.py", line 4
greeting = "Hello " + # FAILS
^
SyntaxError: invalid syntax
I tried line continuation:
greeting = "Hello " + \# FAILS
"World!"
print(greeting)
File "line_continuation.py", line 4
greeting = "Hello " + \# FAILS
^
SyntaxError: unexpected character after line continuation character
If you want to have control over spaces you can simply do:
print("This " # comment 1
"is " # comment 2
"a " # comment 3
"test") # comment 4
s = ("This " # comment 1
"is " # comment 2
"a " # comment 3
"test") # comment 4
print(s)
Outputs:
This is a test
This is a test
Using comma will add a space between each string and is specific to print. The method shown above works for strings in general anywhere.
Note that this will represent a single string, so if you want to inject variables you need to .format on the last line.
The practice of using () around strings are often confused with making a tuple, but it's not a tuple unless it contains a comma.
s = ("Hello")
print(type(s), s)
s = ("Hello",)
print(type(s), s)
Outputs:
<class 'str'> Hello
<class 'tuple'> ('Hello',)
You can break a string into multiple lines by simply putting them one after the other:
a = ("hello " # can use comments
"world")
print(a)
b = "hello " "world" # this also works
print(b)
c = a " again" # but this doesn't, SyntaxError
print(c)
I just figured it out. Adding parentheses around the parts of the string being constructed works:
print("Hello " + # WORKS
"World!")
greeting =("Hello " + # WORKS TOO
"World!")
print(greeting)
I'm quite new to programming (and this is my first post to stackoverflow) however am finding this problem quite difficult. I am supposed to remove a given string in this case (WUB) and replace it with a space. For example: song_decoder(WUBWUBAWUBWUBWUBBWUBC) would give the output: A B C. From other questions on this forums I was able to establish that I need to replace "WUB" and to remove whitespace use a split/join. Here is my code:
def song_decoder(song):
song.replace("WUB", " ")
return " ".join(song.split())
I am not sure where I am going wrong with this as I the error of WUB should be replaced by 1 space: 'AWUBBWUBC' should equal 'A B C' after running the code. Any help or pointing me in the right direction would be appreciated.
You're close! str.replace() does not work "in-place"; it returns a new string that has had the requested replacement performed on it.
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Do this instead:
def song_decoder(song):
song = song.replace("WUB", " ")
return " ".join(song.split())
For example:
In [14]: song_decoder("BWUBWUBFF")
Out[14]: 'B FF'
Strings are immutable in Python. So changing a string (like you try to do with the "replace" function) does not change your variable "song". It rather creates a new string which you immediately throw away by not assigning it to something. You could do
def song_decoder(song):
result = song.replace("WUB", " ") # replace "WUB" with " "
result = result.split() # split string at whitespaces producing a list
result = " ".join(result) # create string by concatenating list elements around " "s
return result
or, to make it shorter (one could also call it less readable) you can
def song_decoder(song):
return " ".join(song.replace("WUB", " ").split())
Do the both steps in a single line.
def song_decoder(song):
return ' '.join(song.replace('WUB',' ').split())
Result
In [95]: song_decoder("WUBWUBAWUBWUBWUBBWUBC")
Out[95]: 'A B C'
I am creating a string, to print the fields in a list, . the fields should be separated by ';', code snippet looks like this( simplified code, not actual )
list = ["abc","xyz","pqr"]
str = "print " + "list[0]" + ";" + "list[2]" # This is dynamically generated
exec (str)
My problem here is, with exec statement, it prints only "xyz" , because of the semi colon. what is the best way to solve this, so that the exec statement prints "xyz;pqr"
You are generating the following code:
print list[0];list[2]
Note that the ; is not quoted. Since a ; is used by Python to separate multiple simple statements on a line, Python executes the print list[0] first, then list[2] (which ends up doing nothing).
You'd have to generate this code instead:
print list[0] + ';' + list[2]
which you could do with:
str = "print " + "list[0]" + " + ';' + " + "list[2]"
However, you should not be using code generation at all. Use standard Python methods to join or format a string. You could use str.format():
print '{};{}'.format(list[0], list[2])
or you could use str.join():
print ';'.join([list[0], list[2]])
If you must vary what code is executed based on some other variables, try to avoid exec still. You could use from __future__ import print_function or encapsulate the print statement in a new function, then call functions dynamically. You can always use a dispatch table to map a string to a function to call, for example.
Try this:
str = "print" + "list[0]" + "';'" + "list[2]"
or
str = "print" + "list[0]" + "/;" + "list[2]"
The problem here is that Python optionally allows semicolons to delimit two separate statements (Compound statements). So when you use exec on the evaluated statement print "abc";"xyz", Python thinks they are two separate statements, hence, only printing "abc".
You could use single quotes around the semicolon to show that it is a string and concatenate them with their surrounding strings:
# Refrain from using list and str as they are built-ins
l = ["abc", "xyz", "pqr"]
s = "print " + "l[0]" + "+';'+" + "l[2]"
exec(s)
i want to print "(" in python
print "(" + var + ")"
but it says:
TypeError: coercing to Unicode: need string or buffer, NoneType found
can somebody help me? that cant be too hard... -.-
Using string formatting:
foo = 'Hello'
print('({})'.format(foo))
maybe a simple print "(" + str(var) + ")"?
it appears that var is None in what you provided. Everything is correct, but var does not contain a string.
Try this:
var = 'Hello World!'
print('(' + var + ')')
Also, your code works well on Python 2.7.4, so long as you pre-define var.
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.