Reputation: 303
I want to do the following split:
input: 0x0000007c9226fc output: 7c9226fc
input: 0x000000007c90e8ab output: 7c90e8ab
input: 0x000000007c9220fc output: 7c9220fc
I use the following line of code to do this but it does not work!
split = element.rpartition('0')
I got these outputs which are wrong!
input: 0x000000007c90e8ab output: e8ab
input: 0x000000007c9220fc output: fc
what is the fastest way to do this kind of split? The only idea for me right now is to make a loop and perform checking but it is a little time consuming.
I should mention that the number of zeros in input is not fixed.
Upvotes: 0
Views: 1486
Reputation: 2159
Regular expression for 0x00000
or its type is (0x[0]+)
and than replace it with space.
import re
st="0x000007c922433434000fc"
reg='(0x[0]+)'
rep=re.sub(reg, '',st)
print rep
Upvotes: 0
Reputation: 2320
format is handy for this:
>>> print '{:x}'.format(0x000000007c90e8ab)
7c90e8ab
>>> print '{:x}'.format(0x000000007c9220fc)
7c9220fc
Upvotes: 1
Reputation: 308206
input[2:].lstrip('0')
That should do it. The [2:]
skips over the leading 0x
(which I assume is always there), then the lstrip('0')
removes all the zeros from the left side.
In fact, we can use lstrip
ability to remove more than one leading character to simplify:
input.lstrip('x0')
Upvotes: 4
Reputation: 87084
Each string can be converted to an integer using int()
with a base of 16. Then convert back to a string.
for s in '0x000000007c9226fc', '0x000000007c90e8ab', '0x000000007c9220fc':
print '%x' % int(s, 16)
Output
7c9226fc 7c90e8ab 7c9220fc
Upvotes: 5
Reputation: 673
If the number of characters in a string is constant then you can use the following code.
input = "0x000000007c9226fc"
output = input[10:]
Also, since you are using rpartition
which is defined as
str.rpartition(sep)
Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.
Since your input can have multiple 0's, and rpartition only splits the last occurrence this a malfunction in your code.
Upvotes: 0
Reputation: 21453
In this particular case you can just do
your_input[10:]
You'll most likely want to properly parse this; your idea of splitting on separation of non-zero does not seem safe at all.
Seems to be the XY problem.
Upvotes: 0