split String at first letter

  • On 09/03/2017 at 22:23, xxxxxxxx wrote:

    Hi there,

    I want to split a String like "0123_456-Name_1438" and get the "Name_1438 ".
    My tryout was this:

    s = "0123_456-Name_1438"
    for c in s:
                if int(c) :
                    print c+" = ",int(c)," ",type(c)
                    print c+" = ",type(c)

    ...a simple try if typecasting can be used to differenciate letters and numbers in a string.

    The console tells: "ValueError: invalid literal for int() with base 10: 'N'"
    Do you have an idea how that can be solved in python?

    edit: I found str.isdigit() that does the trick ;)

  • On 10/03/2017 at 01:23, xxxxxxxx wrote:

    Ok. that's how I solved it:

    def stripLNumbers(s) :
        if s != False:
            num = -1
            for c in s:
                num = num + 1
                if c.isalpha() and c != "-" and c != "_":    #Is there a more elegant way to exclude special characters?
                    return s[num:]

  • On 10/03/2017 at 06:36, xxxxxxxx wrote:

    So basicly you want all after "-"

    If yes simply do

        a = "0123_456-Name_1438"
        split = a.split("-")
        value = str()
        for string in split[1:]:
            value += string
        print value

    But if you jsut want the text look about(google it) regex and re module in python ;)

  • On 10/03/2017 at 07:19, xxxxxxxx wrote:

    Couldn't it be done with a single split call?

    a = "0123_456-Name_1438"
    prefix, name = a.split("-", 1)

  • On 10/03/2017 at 07:23, xxxxxxxx wrote:

    Hahaha completly true ! Didn't know split can take two arguments...

    But mine can take also one line :p

    a = "0123_456-Name_1438"
    value = str().join(a.split("-")[1:])
    print value

  • On 10/03/2017 at 10:51, xxxxxxxx wrote:

    The condition is "at the first letter", not "after the first hyphen" ;)
    Regex is probably the most simple solution.

    import re
    def strip_numbers(s) :
      return re.search('[A-Za-z].*', s).group()

    Or in plain python (very similar to gmak's solution)

    def strip_numbers(s) :
      for i, c in enumerate(s) :
        if c.isalpha() :
          return s[i:]
      raise ValueError('no alphanumerical character in string {!r}'.format(s))


  • On 13/03/2017 at 06:21, xxxxxxxx wrote:

    Nice one, NiklasR!

Log in to reply