The common way is the format() function:
>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'
It works fine with a multi-line format string:
>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.
You can also pass a dictionary with variables:
>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'
The closest thing to what you asked (in terms of syntax) are template strings. For example:
>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'
I should add though that the format() function is more common because it's readily available and it does not require an import line.
The common way is the format() function:
>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'
It works fine with a multi-line format string:
>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.
You can also pass a dictionary with variables:
>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'
The closest thing to what you asked (in terms of syntax) are template strings. For example:
>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'
I should add though that the format() function is more common because it's readily available and it does not require an import line.
You can use Python 3.6's f-strings for variables inside multi-line or lengthy single-line strings. You can manually specify newline characters using \n.
Variables in a multi-line string
string1 = "go"
string2 = "now"
string3 = "great"
multiline_string = (
f"I will {string1} there\n"
f"I will go {string2}.\n"
f"{string3}."
)
print(multiline_string)
I will go there
I will go now
great
Variables in a lengthy single-line string
string1 = "go"
string2 = "now"
string3 = "great"
singleline_string = (
f"I will {string1} there. "
f"I will go {string2}. "
f"{string3}."
)
print(singleline_string)
I will go there. I will go now. great.
Alternatively, you can also create a multiline f-string with triple quotes where literal newlines are considered part of the string. However, any spaces at the start of the line would also be part of the string, so it can mess with code indentation.
multiline_string = f"""I will {string1} there.
I will go {string2}.
{string3}."""
Hey everyone I'm using Python 3 and am pretty new to Python in general. I'm having trouble formatting a multi-line string. I tried prefixing with f as well as just calling .format(variableName) at the end. The f-string variant triggers an invalid syntax error and the .format variant triggers a KeyError.
Is it possible to interpolate variables into a multi-line string? I know old-school string concatenation works, but that has its drawbacks on readability (at least).
Edit: Thanks for the responses! I ended up figuring out that I had curly braces in my string that weren't doubled up. facepalm
How to do multi-line f strings?
Is there any way to use variables in multiline string in Python? - Stack Overflow
Concatenate strings in python in multiline - Stack Overflow
Python: format multitline strings with variables - Stack Overflow
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 achieve 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
You want to say
message = """
Hello, %(foo)s
Sincerely, %(bar)s
""" % {'foo': 'John', 'bar': "Doe"}
Note the s at the end, which makes the general format "%(keyname)s" % {"keyname": "value"}
Try this
message = """
Hello, %(foo)s
Sincerely, %(bar)s
""" % {'foo': "John", 'bar': "Doe"}
I would like to do something like this:
import json
import random
string_device = '''
{
"d": [
{
"deviceId": 1688642,
"pounds": random.randint(100,500),
"voltage": random.uniform(2.0, 6.0)
}
]
}
'''
data = json.loads(string_device)
for device in data['d']:
print(device['voltage'], device['pounds'])I need a string variable so I can call json.loads to create a json object. How do I add the random.randint and random.uniform calls within the multi-line string?
Thanks!