You need to double the {{ and }}:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
Here's the relevant part of the Python documentation for format string syntax:
Answer from Greg Hewgill on Stack OverflowFormat strings contain “replacement fields” surrounded by curly braces
{}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling:{{and}}.
You need to double the {{ and }}:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
Here's the relevant part of the Python documentation for format string syntax:
Format strings contain “replacement fields” surrounded by curly braces
{}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling:{{and}}.
Python 3.6+ (2017)
In the recent versions of Python one would use f-strings (see also PEP498).
With f-strings one should use double {{ or }}
n = 42
print(f" {{Hello}} {n} ")
produces the desired
{Hello} 42
If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:
hello = "HELLO"
print(f"{{{hello.lower()}}}")
produces
{hello}
Videos
I'm confused about the use of the curly brackets in this code from a textbook. I thought the curly brackets are to call dictionaries. but first and last are not, am I right?
def get_formatted_name(first,last):
full_name=f"{first}{last}"
return full_name.title()
>>> import re
>>> oldString = "this is my {{string-d}}"
>>> oldString2 = "this is my second{{ new_string-d }}"
>>> re.sub(r"(\w*-d)", r"(\1)", oldString)
'this is my {{(string-d)}}'
>>> re.sub(r"(\w*-d)", r"(\1)", oldString2)
'this is my second{{ (new_string-d) }}'
Note that this matches "words" assuming that a word is composed of only letters, numbers, and underscores.
Here's a more thorough breakdown of what's happening:
- An
rbefore a string literal means the string is a "raw string". It prevents Python from interpreting characters as an escape sequence. For instance,r"\n"is a slash followed by the letter n, rather than being interpreted as a single newline character. I like to use raw strings for my regex patterns, even though it's not always necessary. - the parentheses surrounding
\w*-dis a capturing group. It indicates to the regex engine that the contents of the group should be saved for later use. - the sequence
\wmeans "any alphanumeric character or underscore". *means "zero or more of the preceding item".\w*together means "zero or more alphanumeric characters or underscores".-dmeans "a hyphen followed by the letter d.
All together, (\w*-d) means "zero or more alphanumeric characters or underscores, followed by a hyphen and the letter d. Save all of these characters for later use."
The second string describes what the matched data should be replaced with. "\1" means "the contents of the first captured group". The parentheses are just regular parentheses. All together, (\1) in this context means "take the saved content from the captured group, surround it in parentheses, and put it back into the string".
If you want to match more characters than just alphanumeric and underscore, you can replace \w with whatever collection of characters you want to match.
>>> re.sub(r"([\w\.\[\]]*-d)", r"(\1)", "{{startingHere[zero1].my_string-d }}")
'{{(startingHere[zero1].my_string-d) }}'
If you also want to match words ending with "-d()", you can match a parentheses pair with \(\) and mark it as optional using ?.
>>> re.sub(r"([\w\.\[\]]*-d(\(\))?)", r"(\1)", "{{startingHere[zero1].my_string-d() }}")
'{{(startingHere[zero1].my_string-d()) }}'
If you want the bracketing to only take place inside double curly braces, you need something like this:
re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)
Breaking that down a bit:
# the target pattern
r'({{\s*)([^}]*-d)(\s*}})'
# ^^^^^^^ capture group 1, opening {{ plus optional space
# ^^^^^^^^^ capture group 2, non-braces plus -d
# ^^^^^^^ capture 3, spaces plus closing }}
The replacement r'\1(\2)\3' just assembles the groups, with
parenthesis around the middle one.
Putting it together:
import re
def quote_string_d(s):
return re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)
print(quote_string_d("this is my {{string-d}}"))
print(quote_string_d("this is my second{{ new_string-d }}"))
print(quote_string_d("this should not be quoted other_string-d "))
Output:
this is my {{(string-d)}}
this is my second{{ (new_string-d) }}
this should not be quoted other_string-d
Note the third instance does not get the parentheses, because it's not inside {{ }}.
How about:
import re
s = "alpha.Customer[cus_Y4o9qMEZAugtnW] ..."
m = re.search(r"\[([A-Za-z0-9_]+)\]", s)
print m.group(1)
For me this prints:
cus_Y4o9qMEZAugtnW
Note that the call to re.search(...) finds the first match to the regular expression, so it doesn't find the [card] unless you repeat the search a second time.
Edit: The regular expression here is a python raw string literal, which basically means the backslashes are not treated as special characters and are passed through to the re.search() method unchanged. The parts of the regular expression are:
\[matches a literal[character(begins a new group[A-Za-z0-9_]is a character set matching any letter (capital or lower case), digit or underscore+matches the preceding element (the character set) one or more times.)ends the group\]matches a literal]character
Edit: As D K has pointed out, the regular expression could be simplified to:
m = re.search(r"\[(\w+)\]", s)
since the \w is a special sequence which means the same thing as [a-zA-Z0-9_] depending on the re.LOCALE and re.UNICODE settings.
You could use str.split to do this.
s = "<alpha.Customer[cus_Y4o9qMEZAugtnW] active_card=<alpha.AlphaObject[card]\
...>, created=1324336085, description='Customer for My Test App',\
livemode=False>"
val = s.split('[', 1)[1].split(']')[0]
Then we have:
>>> val
'cus_Y4o9qMEZAugtnW'