This question already has answers here:
How can I do a line break (line continuation) in Python?
(10 answers)
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 5 months ago.
I have some strings to be concatenated and the resultant string will be quite long. I also have some variables to be concatenated.
How can I combine both strings and variables so the result would be a multiline string?
The following code throws error.
str = "This is a line" +
str1 +
"This is line 2" +
str2 +
"This is line 3" ;
I have tried this too
str = "This is a line" \
str1 \
"This is line 2" \
str2 \
"This is line 3" ;
Please suggest a way to do this.
There are several ways. A simple solution is to add parenthesis:
strz = ("This is a line" +
str1 +
"This is line 2" +
str2 +
"This is line 3")
If you want each "line" on a separate line you can add newline characters:
strz = ("This is a line\n" +
str1 + "\n" +
"This is line 2\n" +
str2 + "\n" +
"This is line 3\n")
Python 3: Formatted Strings
As of Python 3.6 you can use so-called "formatted strings" (or "f strings") to easily insert variables into your strings. Just add an f in front of the string and write the variable inside curly braces ({}) like so:
>>> name = "John Doe"
>>> f"Hello {name}"
'Hello John Doe'
To split a long string to multiple lines surround the parts with parentheses (()) or use a multi-line string (a string surrounded by three quotes """ or ''' instead of one).
1. Solution: Parentheses
With parentheses around your strings you can even concatenate them without the need of a + sign in between:
a_str = (f"This is a line \n{str1}\n"
f"This is line 2 \n{str2}\n"
f"This is line 3") # no variable in this line, so a leading f"" is optional but can be used to properly align all lines
Good to know: If there is no variable in a line, there is no need for a leading f for that line.
Good to know: You could archive the same result with backslashes (\) at the end of each line instead of surrounding parentheses but accordingly to PEP8 you should prefer parentheses for line continuation:
Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
2. Solution: Multi-Line String
In multi-line strings you don't need to explicitly insert \n, Python takes care of that for you:
a_str = f"""This is a line
{str1}
This is line 2
{str2}
This is line 3"""
Good to know: Just make sure you align your code correctly otherwise you will have leading white space in front each line.
By the way: you shouldn't call your variable str because that's the name of the datatype itself.
Sources for formatted strings:
What's new in Python 3.6
PEP498
Python isn't php and you have no need to put $ before a variable name.
a_str = """This is a line
{str1}
This is line 2
{str2}
This is line 3""".format(str1="blabla", str2="blablabla2")
I would add everything I need to concatenate to a list and then join it on a line break.
my_str = '\n'.join(['string1', variable1, 'string2', variable2])
Related
This question already has answers here:
Split a string by a delimiter in python
(5 answers)
Closed 2 years ago.
I am trying to print by breaking a line based on character \n (new line). Below is the example:
line = "This is list\n 1.Cars\n2.Books\n3.Bikes"
I want to print the output as below:
This is list:
1.Cars
2.Books
3.Bikes
I used code as below:
line1 = line.split()
for x in line1:
print(x)
But its printing each word in different line. How to split the string based on only "\n"
Regards,
Arun Varma
The argument to split() specifies the string to use as a delimiter. If you don't give an argument it splits on any whitespace by default.
If you only want to split at newline characters, use
line1 = line.split('\n')
There's also a method specifically for this:
line1 = line.splitlines()
This question already has answers here:
String concatenation without '+' operator
(6 answers)
Closed 6 years ago.
These work for creating a string by defining it's individual elements separately:
str1 = ("a" "b")
# str1 = 'ab'
str2 = ("d"+str1)
# str2 = 'dab'
str3 = ("d" "e" "f")
# str3 = 'def'
But this one fails. Why so?
str3 = ("d"+str1 "e")
# SyntaxError: invalid syntax
What's the work around it?
You're mixing two different things. ("a" "b") looks like it's two strings, but it's really only one; string literals separated by whitespace are automatically concatenated to a single string. It's identical to using ("ab").
On the other hand, you can add two different strings to make a new single string. That's what's happening with ("d"+str1).
The trick in the first example only works with string literals, not with variables or more complicated expressions. So ("d"+str1 "e") doesn't work. You need ("d"+str1+"e"), which is two additions.
P.S. the parentheses are optional, they just group together operations that don't need any additional grouping.
Two string literals next to each other are automatically concatenated; this only works with two literals, not with arbitrary string expressions:
>>> 'str' 'ing' # <- This is ok
'string'
>>> 'str'.strip() + 'ing' # <- This is ok
'string'
>>> 'str'.strip() 'ing' # <- This is invalid
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
The Python Tutorial
More clearer:
This question already has answers here:
In Python, is it possible to escape newline characters when printing a string?
(3 answers)
Closed 7 years ago.
I have a delim list . Now I want to print every element in delim list. But print funtion in python is printing everything except character like '\t' , '\n'. I know it is usual . But can I print this like normal characters or strings.
delim=['\t','\n',',',';','(',')','{','}','[',']','#','<','>']
for c in delim:
print c
It is giving output :
it is printing all the list skipping \t and \n
Change them to raw string literals by prefixing a r:
>>> print '\n'
>>> print r'\n'
\n
For your example this would mean:
delim=[r'\t',r'\n',',',';','(',')','{','}','[',']','#','<','>']
for c in delim:
print c
If you just want to print them differently use repr
for c in delim:
print repr(c)
Note: You will also see additional ' at the beginning and end of each string.
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 7 years ago.
I have this code
print "/*!",your_name.upper(),"*/";
where your_name is the data the user inputs.
How can I edit the code above to tell the system to remove any whitespace?
UPDATE:
If i print the code, i'll get
/*! your_name */
I want to remove the whitspaces between /*! your_name */
The spaces are inserted by the print statement when you pass in multiple expressions separated by commas. Don't use the commas, but build one string, so you pass in just the one expression:
print "/*!" + your_name.upper() + "*/"
or use string formatting with str.format():
print "/*!{0}*/".format(your_name.upper())
or the older string formatting operation:
print "/*!%s*/" % your_name.upper()
Or use the print() function, setting the separator to an empty string:
from __future__ import print_function
print("/*!", your_name.upper(), "*/", sep='')
The white spaces are inserted by print when you use multiple expressions separated by commas.
Instead of using commas, try :
print "/*!" + your_name.upper() + "*/"
This question already has answers here:
Split a string by spaces -- preserving quoted substrings -- in Python
(16 answers)
Closed 9 years ago.
I have my data as below
string = ' streptococcus 7120 "File being analysed" rd873 '
I tried to split the line using n=string.split() which gives the below result:
[streptococcus,7120,File,being,analysed,rd873]
I would like to split the string ignoring white spaces in " "
# output expected :
[streptococcus,7120,File being analysed,rd873]
Use re.findall with a suitable regex. I'm not sure what your error cases look like (what if there are an odd number of quotes?), but:
filter(None, it.chain(*re.findall(r'"([^"]*?)"|(\S+)', ' streptococcus 7120 "File being analysed" rd873 "hello!" hi')))
> ['streptococcus',
'7120',
'File being analysed',
'rd873',
'hello!',
'hi']
looks right.
You want shlex.split, which gives you the behavior you want with the quotes.
import shlex
string = ' streptococcus 7120 "File being analysed" rd873 '
items = shlex.split(string)
This won't strip extra spaces embedded in the strings, but you can do that with a list comprehension:
items = [" ".join(x.split()) for x in shlex.split(string)]
Look, ma, no regex!