Reputation: 5127
I have a variable text whose value is like below,I need strip of trailing digits,is there a python built-in function to do it..if not,please suggest how can this be done in python
e.g. -text=A8980BQDFZDD1701209.3
=> -A8980BQDFZDD
Upvotes: 2
Views: 12977
Reputation: 12607
For the sake of completion, how about this syntax in python3 ?
from string import digits
print('123abc382'.rstrip(digits))
Upvotes: 6
Reputation: 113915
In [36]: myStr = '-text=A8980BQDFZDD1701209.3'
In [37]: print '-'+myStr.rpartition('=')[-1].rstrip('1234567890.')
-A8980BQDFZDD
Upvotes: 3
Reputation: 1464
The first step is to understand what information the strings are encoding, and how you decode it as you read it. That tells you what the patterns in your data are, and those will determine how you'll manipulate the string to extract the information in Python.
If you just need to lose the last few numbers, you could rstrip
them easily enough. This is assuming you want to change "-text=" to "-", as you imply in the question:
input = '-text=A8980BQDFZDD1701209.3'
text = input.split('=')[1]
output = '-' + text.rstrip('1234567890.')
This is a potentially risky approach since it also assumes the numeric suffix will never have any alphabetic characters in it, and that the half you want to keep will never end in a character you're passing to rstrip
. If either of those things are not always true of your data, this solution will give you bad results and you'll need to find a more accurate pattern.
For example, if the 'keep' part is always 12 characters long, you would want to take a string slice by replacing line 3 of my example with this:
output = '-' + text[:12]
But ultimately, it depends on what these strings are, and what rules define how the different halves are formed in the first place.
Upvotes: 0
Reputation: 2885
print 'text=A8980BQDFZDD1701209.3'.rstrip('1234567890.')[5:]
will do everything required. The slicing at the end is something of a hack, however.
Upvotes: 0