This question already has answers here:
How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?
(23 answers)
Closed 6 years ago.
again :)
I found this bit of code
col_width=[13,11]
header=['First Name','Last Name']
format_specs = ["{{:{}}}".format(col_width[i]) for i in range(len(col_width))]
lheader=[format_specs[i].format(self.__header[i]) for i in range(nb_columns)]
How Python evaluate this statement? Why we use three { when we have one element to format in every iteration?
when you do {{}}, python skips the replacement of {} and makes it the part of string. Below is the sample example to explain this:
>>> '{{}}'.format(3) # with two '{{}}'
'{}' # nothing added to the string, instead made inner `{}` as the part of string
>>> '{{{}}}'.format(3) # with three '{{{}}}'
'{3}' # replaced third one with the number
Similarly, your expression is evaluating as:
>>> '{{:{}}}'.format(3)
'{:3}' # during creation of "format_specs"
For details, refer: Format String Syntax document.
Related
This question already has answers here:
Combine f-string and raw string literal
(5 answers)
Closed 1 year ago.
I have an issue in python. My original regex expression is:
f"regex(metrics_api_failure\.prod\.[\w_]+\.{method_name}\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"
(method_name is a local variable) and I got a lint warning:
"[FLAKE8 W605] invalid escape sequence '\.'Arc(W605)"
Which looks like recommends me to use r as the regex prefix. But if I do:
r"regex(metrics_api_failure\.prod\.[\w_]+\.{method_name}\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"
The {method_name} becomes the string type rather than a passed in variable.
Does anyone have an idea how to solve this dilemma?
Pass in the expression:
r"regex(metrics_api_failure\.prod\.[\w_]+\." + method_name + r"\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"
Essentially, use Python string concatenation to accomplish the same thing that you were doing with the brackets. Then, r"" type string escaping should work.
or use a raw format string:
rf"regex(metrics_api_failure\.prod\.[\w_]+\.{method_name}\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"
This question already has answers here:
python - how to apply backspaces to a string [closed]
(2 answers)
Closed 1 year ago.
As a simple use case in Python, I wish to convert some encoded text and set it equal to a variable or dictionary key as would be printed on screen. This issue came about by piping some std out to memory from a command line function where some of the text didn't seem to be properly interpreted in python.
Example:
myVar = "N\x08NA\x08AM\x08ME\x08E"
print(myVar)
="NAME"
When myVar is input as a dictionary key, I get the following result:
myDict = {}
myDict[myVar] = 'foobar'
print(myDict.keys())
=dict_keys(['N\x08NA\x08AM\x08ME\x08E'])
How can I make myDict.keys() = dict_keys(['Name'])?
Same question for a variable where
myVar = "NAME"
rather than 'N\x08NA\x08AM\x08ME\x08E'
I've tried variants of myVar.encode() and str(myVar) with no success.
You can easily remove every character that would be erased by a backspace (\x08 or \b) with a regular expression.
import re
re.sub('.\x08', '', "N\x08NA\x08AM\x08ME\x08E")
='NAME'
This question already has answers here:
member variable string gets treated as Tuple in Python
(3 answers)
Closed 4 years ago.
I am new to python and trying to experiment something with strings.
I have below commands.
s7="hello",'world'
print(s7)
Output was : ('hello', 'world')
As per my understanding, it should not print angular braces and it should not print hello in single quotes. Could you help me in understanding this?
Those are not angular braces. They are parentheses, and they indicate that what you are printing is a tuple. A tuple is kind of sequence, in this case a pair of strings.
Your first string is "hello", and your second string is 'world'.
You could have expressed them as 'hello' and "world" and produced exactly the same strings. The quote marks (either kind) are there to indicate the content of the string, but they are not part of the content of the string.
You assigned not 1, but 2 strings (in a tuple) to s7, which explains how it was printed.
s7 = "\"hello\",'world'"
seems like it would assign the string you want. (Note the use of \"to indicate a " inside of a string surrounded by "s, as #NielsHenkens points out.)
This question already has answers here:
Having both single and double quotation in a Python string
(9 answers)
Closed 5 years ago.
I'd like to save the following characters 'bar" as a string variable, but it seems to be more complicated than I thought :
foo = 'bar" is not a valid string.
foo = ''bar"' is not a valid string either.
foo = '''bar"'' is still not valid.
foo = ''''bar"''' actually saves '\'bar"'
What is the proper syntax in this case?
The last string saves '\'bar"' as the representation, but it is the string you're looking for, just print it:
foo = ''''bar"'''
print(foo)
'bar"
when you hit enter in the interactive interpreter you'll get it's repr which escapes the second ' to create the string.
Using a triple quoted literal is the only way to define this without explicitly using escapes. You can get the same result by escaping quotes:
print('\'foo"')
'foo"
print("'foo\"")
'foo"
This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 6 years ago.
I have make a set of names in this form: 's1', 's2', ..., 's100'. I thought I can do that easily via looping:
for i in range(100):
print ('s'.format(i+1))
format here does not append the numbers. I only get ss..ss without the numbers being concatenated in single quote. I know how to do this in Java but I am not that much expert in Python. Thank you
You need to have a placeholder in the format string:
Perform a string formatting operation. The string on which this method
is called can contain literal text or replacement fields delimited by
braces {}. Each replacement field contains either the numeric index of
a positional argument, or the name of a keyword argument.
for i in range(100):
print ('s{0}'.format(i+1))
If you use 3.6, then you can take advantage of the new 'Literal String Interpolation', and do the following:
for i in range(100):
print(f's{i + 1}')
For more details on this feature, check out PEP 498 -- Literal String Interpolation