Remove hex character from string in Python - python

I'm trying to remove one character from a string o hex values but I can't find a solution to make this work. If I print remove2 I get the string "\x41", but when I print buffer I get ABCD". The thing is I don't understand why when I print remove2 I get the string hex format and when I print buffer I get the ASCII format. I think it is in the root of the problem. How could I fix this using Python 2?
>>> buffer = "\x41\x42\x43\x44"
>>> remove = raw_input("Enter hex value to remove: ")
Enter hex value to remove: 42
>>> remove2 = "\\x" + remove
>>> print buffer
ABCD
>>> print remove2
\x42
>>> buffer2 = buffer.replace(remove2, '')
>>> print buffer2
ABCD
I wish buffer2 = "\x41\x43\x44".

Here's the problem:
remove2 = "\\x" + remove
You can't programmatically build escape sequences like that. Instead, do this:
remove2 = chr(int(remove, 16))
Alternatively, you'd have to make buffer contain the literal backslashes instead of the escaped characters:
buffer = "\\x41\\x42\\x43\\x44"

The problem being is that if you print out remove without the print, you'll see
>>> remove2
'\\x42'
that the \ is staying there and not making it hexadecimal. For that you need to do:
remove.decode('hex')
so the code being:
>>> buffer = "\x41\x42\x43\x44"
>>> remove = raw_input("Enter hex value to remove: ")
Enter hex value to remove: 42
>>> remove2=remove.decode('hex')
>>> buffer.replace(remove2, '')
'ACD'
Does that help/answers your question?

You will need to escape the \ in your buffer string o/w it will be treated as hex value. So,
>>> buffer="\\x41\\x42\\x43"`<br>
>>> remove = "42"`<br>
>>> remove = "\\x" + remove` <br>
>>> buffer = buffer.replace(remove, '')` <br>
>>> print buffer #prints \\\x41\\\x43

You can use filter() and construct a filtered bytes object using the user input of "42" and original bytes (just a string in Python2).
>>> inp = "42"
>>> filter(lambda x: x != chr(int(inp, 16)), 'ABCD')
'ACD'
Python 3
>>> inp = "42"
>>> bytes(filter(lambda x: x != int(inp, 16), b'ABCD'))
b'ACD'
Anyway, simpler to use replace(), this is just an alternative way to filter out specific values from a bytes object. It illustrates the basic idea other answers point out. The user input needs to be correctly converted to the value you intend to remove.
When the interp renders the output, the backslashes aren't represented in bytes or str objects for characters/values that correspond to utf-8 or ascii printable characters. If there isn't a corresponding printable character, then an escaped version of the value will be presented in output.

Related

Change ASCII to characters in string

i'm trying to convert ASCII values in string to normal characters, but whatever i'll try to do, i'll get output like
this\032is\032my\032\output\000
and I need
this is my output
Thanks for your help!
I solved it with
import re
def replace(match):
return chr(int(match.group(1)))
aux = str(element.text)
regex = re.compile(r"\\(\d{1,3})")
new = regex.sub(replace, aux)
where element.text is string i need to convert
\032 is octal for the decimal number 26, so it is not in fact a space character, if you use a hex value with the correct number, you should get what you want. 0x20 == 32 below
>>> s = 'this\x20is\x20my\x20\output\00'
>>> print(s)
this is my \output

escape a string which contains non-ascii

now I have string s = "\\u653e"
I want to convert this string into s = "\u653e"
I try to make it clear:
# this is what I want
>>s
>>'\u653e'
# this is not what I want, print will escape the string automatically
>>print s
>>\653e
how can I do that?
the original question is that
I have a string s = u'\u653e', [s] = [u'\u653e']
So I want to remove the u, that is, [s] = ['\u653e']
so I just use the command ast.literal_eval(json.dumps(r)) to get the above string "\\u653e"
UPDATE
Thanks tdelaney
Creating a string from an entire list causes my problem. What I should to do is using a unicode string to start with and build the list from its individual elements instead of the entire list. For more details you can see his answer.
s is a single unicode character. "\u653e is a literal encoding that python uses to express unicode characters in ascii text. The unicode_escape codec converts between these types.
>>> s = u'\u653e'
>>> print type(s), len(s), s
<type 'unicode'> 1 放
>>> encoded = s.encode('unicode_escape')
>>> print type(encoded), len(encoded), encoded
<type 'str'> 6 \u653e
In your example just do
s = u'\u653e'
somelist = [s.encode('unicode_escape')]
>>> print somelist
['\\u653e']
>>> print somelist[0]
\u653e
update
From your comments, your problem may be how you create your command string. There seems to be a problem with the python representation of a string verses the string itself. Use a unicode string to start with and build the list from its individual elements instead of the entire list.
>>> excel = [u'\u4e00', u'\u4e8c', u'\u4e09']
>>> cmd = u'create vertex v set s = [{}]'.format(u','.join(excel))
>>> cmd
u'create vertex v set s = [\u4e00,\u4e8c,\u4e09]'
>>> print cmd
create vertex v set s = [一,二,三]

as I hold the string of hexadecimal format without encoding the string?

The general problem is that I need the hexadecimal string stays in that format to assign it to a variable and not to save the coding?
no good:
>>> '\x61\x74'
'at'
>>> a = '\x61\x74'
>>> a
'at'
works well, but is not as:
>>> '\x61\x74'
'\x61\x74' ????????
>>> a = '\x61\x74'
>>> a
'\x61\x74' ????????
Use r prefix (explained on SO)
a = r'\x61\x74'
b = '\x61\x74'
print (a) #prints \x61\x74
print (b) # prints at
It is the same data. Python lets you specify a literal string using different methods, one of which is to use escape codes to represent bytes.
As such, '\x61' is the same character value as 'a'. Python just chooses to show printable ASCII characters as printable ASCII characters instead of the escape code, just because that makes working with bytestrings that much easier.
If you need the literal slash, x character and the two digit 6 and 1 characters (so a string of length 4), you need to double the slash or use raw strings.
To illustrate:
>>> '\x61' == 'a' # two notations for the same value
True
>>> len('\x61') # it's just 1 character
1
>>> '\\x61' # escape the escape
'\\x61'
>>> r'\x61' # or use a raw literal instead
'\\x61'
>>> len('\\x61') # which produces 4 characters
4

How do I convert a single character into its hex ASCII value in Python?

I am interested in taking in a single character.
c = 'c' # for example
hex_val_string = char_to_hex_string(c)
print hex_val_string
output:
63
What is the simplest way of going about this? Any predefined string library stuff?
There are several ways of doing this:
>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'
On Python 2, you can also use the hex encoding like this (doesn't work on Python 3+):
>>> "c".encode("hex")
'63'
This might help
import binascii
x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')
print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374
x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'
x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test
This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').
Considering your input string is in the inputString variable, you could simply apply .encode('utf-8').hex() function on top of this variable to achieve the result.
inputString = "Hello"
outputString = inputString.encode('utf-8').hex()
The result from this will be 48656c6c6f.
You can do this:
your_letter = input()
def ascii2hex(source):
return hex(ord(source))
print(ascii2hex(your_letter))
For extra information, go to:
https://www.programiz.com/python-programming/methods/built-in/hex
to get ascii code use ord("a");
to convert ascii to character use chr(97)

How do I lowercase a string in Python?

Is there a way to convert a string to lowercase?
"Kilometers" → "kilometers"
Use str.lower():
"Kilometer".lower()
The canonical Pythonic way of doing this is
>>> 'Kilometers'.lower()
'kilometers'
However, if the purpose is to do case insensitive matching, you should use case-folding:
>>> 'Kilometers'.casefold()
'kilometers'
Here's why:
>>> "Maße".casefold()
'masse'
>>> "Maße".lower()
'maße'
>>> "MASSE" == "Maße"
False
>>> "MASSE".lower() == "Maße".lower()
False
>>> "MASSE".casefold() == "Maße".casefold()
True
This is a str method in Python 3, but in Python 2, you'll want to look at the PyICU or py2casefold - several answers address this here.
Unicode Python 3
Python 3 handles plain string literals as unicode:
>>> string = 'Километр'
>>> string
'Километр'
>>> string.lower()
'километр'
Python 2, plain string literals are bytes
In Python 2, the below, pasted into a shell, encodes the literal as a string of bytes, using utf-8.
And lower doesn't map any changes that bytes would be aware of, so we get the same string.
>>> string = 'Километр'
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.lower()
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.lower()
Километр
In scripts, Python will object to non-ascii (as of Python 2.5, and warning in Python 2.4) bytes being in a string with no encoding given, since the intended coding would be ambiguous. For more on that, see the Unicode how-to in the docs and PEP 263
Use Unicode literals, not str literals
So we need a unicode string to handle this conversion, accomplished easily with a unicode string literal, which disambiguates with a u prefix (and note the u prefix also works in Python 3):
>>> unicode_literal = u'Километр'
>>> print(unicode_literal.lower())
километр
Note that the bytes are completely different from the str bytes - the escape character is '\u' followed by the 2-byte width, or 16 bit representation of these unicode letters:
>>> unicode_literal
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> unicode_literal.lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
Now if we only have it in the form of a str, we need to convert it to unicode. Python's Unicode type is a universal encoding format that has many advantages relative to most other encodings. We can either use the unicode constructor or str.decode method with the codec to convert the str to unicode:
>>> unicode_from_string = unicode(string, 'utf-8') # "encoding" unicode from string
>>> print(unicode_from_string.lower())
километр
>>> string_to_unicode = string.decode('utf-8')
>>> print(string_to_unicode.lower())
километр
>>> unicode_from_string == string_to_unicode == unicode_literal
True
Both methods convert to the unicode type - and same as the unicode_literal.
Best Practice, use Unicode
It is recommended that you always work with text in Unicode.
Software should only work with Unicode strings internally, converting to a particular encoding on output.
Can encode back when necessary
However, to get the lowercase back in type str, encode the python string to utf-8 again:
>>> print string
Километр
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.decode('utf-8')
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower().encode('utf-8')
'\xd0\xba\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.decode('utf-8').lower().encode('utf-8')
километр
So in Python 2, Unicode can encode into Python strings, and Python strings can decode into the Unicode type.
With Python 2, this doesn't work for non-English words in UTF-8. In this case decode('utf-8') can help:
>>> s='Километр'
>>> print s.lower()
Километр
>>> print s.decode('utf-8').lower()
километр
Also, you can overwrite some variables:
s = input('UPPER CASE')
lower = s.lower()
If you use like this:
s = "Kilometer"
print(s.lower()) - kilometer
print(s) - Kilometer
It will work just when called.
Don't try this, totally un-recommend, don't do this:
import string
s='ABCD'
print(''.join([string.ascii_lowercase[string.ascii_uppercase.index(i)] for i in s]))
Output:
abcd
Since no one wrote it yet you can use swapcase (so uppercase letters will become lowercase, and vice versa) (and this one you should use in cases where i just mentioned (convert upper to lower, lower to upper)):
s='ABCD'
print(s.swapcase())
Output:
abcd
I would like to provide the summary of all possible methods
.lower() method.
str.lower()
combination of str.translate() and str.maketrans()
.lower() method
original_string = "UPPERCASE"
lowercase_string = original_string.lower()
print(lowercase_string) # Output: "uppercase"
str.lower()
original_string = "UPPERCASE"
lowercase_string = str.lower(original_string)
print(lowercase_string) # Output: "uppercase"
combination of str.translate() and str.maketrans()
original_string = "UPPERCASE"
lowercase_string = original_string.translate(str.maketrans(string.ascii_uppercase, string.ascii_lowercase))
print(lowercase_string) # Output: "uppercase"
lowercasing
This method not only converts all uppercase letters of the Latin alphabet into lowercase ones, but also shows how such logic is implemented. You can test this code in any online Python sandbox.
def turnIntoLowercase(string):
lowercaseCharacters = ''
abc = ['a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
for character in string:
if character not in abc:
lowercaseCharacters += character
elif abc.index(character) <= 25:
lowercaseCharacters += character
else:
lowercaseCharacters += abc[abc.index(character) - 26]
return lowercaseCharacters
string = str(input("Enter your string, please: " ))
print(turnIntoLowercase(string = string))
Performance check
Now, let's enter the following string (and press Enter) to make sure everything works as intended:
# Enter your string, please:
"PYTHON 3.11.2, 15TH FeB 2023"
Result:
"python 3.11.2, 15th feb 2023"
If you want to convert a list of strings to lowercase, you can map str.lower:
list_of_strings = ['CamelCase', 'in', 'Python']
list(map(str.lower, list_of_strings)) # ['camelcase', 'in', 'python']

Categories

Resources