Python Trailing L Problem - python

I'm using Python to script some operations on specific locations in memory (32 bit addresses) in an embedded system.
When I'm converting these addresses to and from strings, integers and hex values a trailing L seems to appear. This can be a real pain, for example the following seemingly harmless code won't work:
int(hex(4220963601))
Or this:
int('0xfb96cb11L',16)
Does anyone know how to avoid this?
So far I've come up with this method to strip the trailing L off of a string, but it doesn't seem very elegant:
if longNum[-1] == "L":
longNum = longNum[:-1]

If you do the conversion to hex using
"%x" % 4220963601
there will be neither the 0x nor the trailing L.

Calling str() on those values should omit the trailing 'L'.

Consider using rstrip. For example:
result.rstrip("L")

This is what I did: int(variable_which_is_printing_as_123L) and it worked for me. This will work for normal integers.

this could help somebody:
>>>n=0xaefa5ba7b32881bf7d18d18e17d3961097548d7cL
>>>print "n=","%0s"%format(n,'x').upper()
n= AEFA5BA7B32881BF7D18D18E17D3961097548D7C

Related

Why Python hex() function is not working on a 64 bit binary digit that starts with 1? [duplicate]

I'm using Python to script some operations on specific locations in memory (32 bit addresses) in an embedded system.
When I'm converting these addresses to and from strings, integers and hex values a trailing L seems to appear. This can be a real pain, for example the following seemingly harmless code won't work:
int(hex(4220963601))
Or this:
int('0xfb96cb11L',16)
Does anyone know how to avoid this?
So far I've come up with this method to strip the trailing L off of a string, but it doesn't seem very elegant:
if longNum[-1] == "L":
longNum = longNum[:-1]
If you do the conversion to hex using
"%x" % 4220963601
there will be neither the 0x nor the trailing L.
Calling str() on those values should omit the trailing 'L'.
Consider using rstrip. For example:
result.rstrip("L")
This is what I did: int(variable_which_is_printing_as_123L) and it worked for me. This will work for normal integers.
this could help somebody:
>>>n=0xaefa5ba7b32881bf7d18d18e17d3961097548d7cL
>>>print "n=","%0s"%format(n,'x').upper()
n= AEFA5BA7B32881BF7D18D18E17D3961097548D7C

Python insert a line break in a string after character "X"

What is the python syntax to insert a line break after every occurrence of character "X" ? This below gave me a list object which has no split attribute error
for myItem in myList.split('X'):
myString = myString.join(myItem.replace('X','X\n'))
myString = '1X2X3X'
print (myString.replace ('X', 'X\n'))
You can simply replace X by "X\n"
myString.replace("X","X\n")
Python 3.X
myString.translate({ord('X'):'X\n'})
translate() allows a dict, so, you can replace more than one different character at time.
Why translate() over replace() ? Check translate vs replace
Python 2.7
myString.maketrans('X','X\n')
A list has no split method (as the error says).
Assuming myList is a list of strings and you want to replace 'X' with 'X\n' in each once of them, you can use list comprehension:
new_list = [string.replace('X', 'X\n') for string in myList]
Based on your question details, it sounds like the most suitable is str.replace, as suggested by #DeepSpace. #levi's answer is also applicable, but could be a bit of a too big cannon to use.
I add to those an even more powerful tool - regex, which is slower and harder to grasp, but in case this is not really "X" -> "X\n" substitution you actually try to do, but something more complex, you should consider:
import re
result_string = re.sub("X", "X\n", original_string)
For more details: https://docs.python.org/2/library/re.html#re.sub

Python strip unexpected behavior

I was stripping a file name in python for routing purposes and I was getting some unexpected behavior with the python strip function. I've read the docs and searched online but have not been able to find an explanation for the following behavior:
"Getting-Started.md".strip('.md')
Out[29]: 'Getting-Starte'
But if it is any other character aside from 'd' to the left of the period, it works properly:
"Getting-StarteX.md".strip('.md')
Out[30]: 'Getting-StarteX'
It seems like there is something similar to a mirroring going on 'd. md'. I'm doing a double strip to get by this for now, but I was just curious of why this occurs.
Thank you.
strip() would strip all the characters provided in the argument - in your case ., m and d.
Instead, you can use os.path.splitext():
import os
os.path.splitext("Getting-StarteX.md")[0]
If there is only one ".md" appearing at the end of the testing string, you can also use
"Getting-Started.md".split('.md')[0]
Thanks #Carpetsmoker remind me the assumption.

How can I get Python to use upper case letters when printing hexadecimal values?

In Python v2.6 I can get hexadecimal for my integers in one of two ways:
print(("0x%x")%value)
print(hex(value))
However, in both cases, the hexadecimal digits are lower case. How can I get these in upper case?
Capital X (Python 2 and 3 using sprintf-style formatting):
print("0x%X" % value)
Or in python 3+ (using .format string syntax):
print("0x{:X}".format(value))
Or in python 3.6+ (using formatted string literals):
print(f"0x{value:X}")
Just use upper().
intNum = 1234
hexNum = hex(intNum).upper()
print('Upper hexadecimal number = ', hexNum)
Output:
Upper hexadecimal number = 0X4D2
print(hex(value).upper().replace('X', 'x'))
Handles negative numbers correctly.
By using uppercase %X:
>>> print("%X" % 255)
FF
Updating for Python 3.6 era: Just use 'X' in the format part, inside f-strings:
print(f"{255:X}")
(f-strings accept any valid Python expression before the : - including direct numeric expressions and variable names).
The more Python 3 idiom using f-strings would be:
value = 1234
print(f'0x{value:X}')
'0x4D2'
Notes (and why this is not a duplicate):
shows how to avoid capitalizing the '0x' prefix, which was an issue in other answers
shows how to get variable interpolation f'{value}'; nobody actually ever puts (hardcoded) hex literals in real code. There are plenty of pitfalls in doing variable interpolation: it's not f'{x:value}' nor f'{0x:value}' nor f'{value:0x}' nor even f'{value:%x}' as I also tried. So many ways to trip up. It still took me 15 minutes of trial-and-error after rereading four tutorials and whatsnew docs to get the syntax. This answer shows how to get f-string variable interpolation right; others don't.

What's the Ruby equivalent of Python's output[:-1]?

In Python, if I want to get the first n characters of a string minus the last character, I do:
output = 'stackoverflow'
print output[:-1]
What's the Ruby equivalent?
I don't want to get too nitpicky, but if you want to be more like Python's approach, rather than doing "StackOverflow"[0..-2] you can do "StackOverflow"[0...-1] for the same result.
In Ruby, a range with 3 dots excludes the right argument, where a range with two dots includes it. So, in the case of string slicing, the three dots is a bit more close to Python's syntax.
Your current Ruby doesn't do what you describe: it cuts off the last character, but it also reverses the string.
The closest equivalent to the Python snippet would be
output = 'stackoverflow'
puts output[0...-1]
You originally used .. instead of ... (which would work if you did output[0..-2]); the former being closed–closed the latter being closed–open. Slices—and most everything else—in Python are closed–open.
"stackoverflow"[0..-2] will return "stackoverflo"
If all you want to do is remove the last character of the string, you can use the 'chop' method as well:
puts output.chop
or
puts output.chop!
If you only want to remove the last character, you can also do
output.chop

Categories

Resources