data='115Z2113-3-777-55789ABC7777'
I have a string in the above format.
I want to remove 'ABC7777' from it. If there are any characters other then numbers after the right most '-' symbol, then only the string preceeding it should be retained.i.e., '115Z2113-3-777-55789ABC7777' should be stored in data. 'ABC7777' should be stripped off.
Please help me out with this.

Thanks & Regards,
Dinil

Recommended Answers

All 3 Replies

Function indexList() returns a list of indices of '-' in the string. Function strip_chrs() strips the trailing characters from the first occurrence of a letter after the last '-'.

def indexList(s, item, i=0):
    """
    Return an index list of all occurrances of 'item' in string/list 's'.
    Optional start search position 'i'
    """
    i_list = []
    while True:
        try:
            i = s.index(item, i)
            i_list.append(i)
            i += 1
        except:
            break
    return i_list

def strip_chrs(s, subs):
    for i in range(indexList(s, subs)[-1], len(s)):
        if s[i+1].isalpha():
            return data[:i+1]

data = '115Z2113-3-777-55789ABC7777'
print strip_chrs(data, '-')

Output:
>>> 115Z2113-3-777-55789
>>>

>>> import re
>>> data = '115Z2113-3-777-55789ABC7777'
>>> ds = data.split('-')
>>> out = '-'.join(ds[0:-1] + [re.split('[A-Z]', ds[-1])[0]])
>>> out
'115Z2113-3-777-55789'

HTH

You can also use rfind to find the rightmost "-", which returns the location of the character. A slice using this location+1 will give you the string after the final "-", and you can use isdigit to tell if there are alpha characters.

def numbers_only(str_in):
   new_str=""
   if False == str_in.isdigit():
      for chr in str_in:
         if not chr.isdigit():
            return new_str    ## exit on first alpha character
         new_str += chr
   else:
      new_str = str_in
   return new_str

data='115Z2113-3-777-55789ABC7777'
x = data.rfind("-")
end_str = data[x+1:]

new_str = numbers_only(end_str)
print "new_str =", new_str
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.