This is probably a very simple question for some, but it has me stumped. Can you use variables within python\'s triple-quotes?
In the following example, how do use
Yes! Starting from Python 3.6 you can use the f
strings for this: They're interpolated in place, so mystring
would have the desired value after the mystring = ...
line:
wash_clothes = 'tuesdays'
clean_dishes = 'never'
mystring = f"""I like to wash clothes on {wash_clothes}
I like to clean dishes {clean_dishes}
"""
print(mystring)
Should you need to add a literal {
or }
in the string, you would just double it:
if use_squiggly:
kind = 'squiggly'
else:
kind = 'curly'
print(f"""The {kind} brackets are:
- '{{', or the left {kind} bracket
- '}}', or the right {kind} bracket
""")
would print, depending on the value of use_squiggly
, either
The squiggly brackets are:
- '{', or the left squiggly bracket
- '}', or the right squiggly bracket
or
The curly brackets are:
- '{', or the left curly bracket
- '}', or the right curly bracket