How to correctly (re) interpret encoded text? [duplicate] - python

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'

Related

Compare strings with unicode characters in python [duplicate]

This question already has answers here:
How do I compare a Unicode string that has different bytes, but the same value?
(3 answers)
Closed 2 years ago.
Here is the substring Ritē
I have two strings, one is from the extracted file name by zipfile. I used filename.encode('cp437').decode('utf-8') to have all the paths extracted correctly. The other one is read from a .plist using plistlib.readPlist(). Both are printed correctly using print(). However, they are not the same in comparison. I tried to encode both of them in utf-8, here is what they look like:
Rite\xcc\x84
Rit\xc4\x93
One interprets character e and - on top, the other one interprets the 'LATIN SMALL LETTER E WITH MACRON'Does any one have any advice on this, in order to compare the two strings? Thank you in advance
Based on the comments it sounds like this is what you're looking for:
import unicodedata
foo = 'Rit\u0113'
bar = 'Rite\u0304'
print(foo, bar)
print(unicodedata.normalize('NFD', foo))
print(unicodedata.normalize('NFD', bar))
assert unicodedata.normalize('NFD', foo) == unicodedata.normalize('NFD', bar)
I selected NFD as the form, but you may prefer NFC.

Python f-string name "blabla is not defined" error when trying to insert a string into string [duplicate]

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 2 years ago.
Okay, so to start off I am trying to insert a string into code that I made into string.
Here's what I mean:
x="achievement"
data= f"{x}_scores:[{ score: { type: number}},"
Trying to insert x into the the string using f-string.
But it keeps saying
NameError: name 'score' is not defined
This is a test I'm doing for a bigger project.
Note that the string I'm inserting into is code I turned into string because I need to insert 100+ words into similar strings, and I can't do it by hand. I'm just trying to generate a list and copy and paste the output elsewhere.
I absolutely need to insert it into that format. Can I get some help?
Here is how:
x = "achievement"
data = f"{x}_scores:""[{score: { type: number}},"
print(data)
Output:
achievement_scores:[{score: { type: number}},
The "" I inserted in between {x}_scores: and [{score: { type: number}}, tells python to only perform the f on the first half of the string, and then append the second half after the evaluation.

How do I put a string and a variable in the same print? [duplicate]

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 3 years ago.
I'm coding a little game and I want a score system. I have two variables that I want to display as "The current score is: X/X" but its not including the variables
I've tried putting it in 'quotes' put it didn't work
U = 2
L = 3
print("Current score: U/L")
I want it to be "Current score: 2/3"
print(f"Current score: {U}/{L}")
Strings enclosed with simple quotes or double-quotes imply that all characters in it are just literal text - they are not interpreted as variables.
From Python 3.6, the prefix f for the quotes delimiting the string denotes an special literal which can include Python expressions inside - including variables. Still, to separate these variables from plain text (and avoid unpredictable substitutions), these expressions have to be further delimited by { }, inside the string.
Prior to Python 3.6, one would have to do it in two separate steps: create a plain string with special markers were the variables contents would be inserted, and then call the .format method on the string. (or, there is an older method using the % operator instead). Fully documenting these other methods would be long - but a short form would require one to write:
print("Current score: {}/{}".format(U, L))

How to write a string starting with ' and ending with " in Python? [duplicate]

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"

format() function in python - Usage of multiple curly brackets {{{}}} [duplicate]

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.

Categories

Resources