str information

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nicstel
    New Member
    • Jun 2008
    • 20

    str information

    How to print only the number in:

    x = 1p
    if I print x = 1p
    but in want only = 1

    Thank You
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    I'm guessing you mean x = "1p"?
    You're trying to take an integer value off the front of a string, right?
    So if x = "123abc" you want 123, and if x = "10307a10c5 2" you want 10307, right? I don't know of a function that does this for you in Python, but I can think of some code that would, although it probably isn't very efficient code. You could make a loop that takes larger portions of the string each iteration, tries to convert them to integers with the int() function, and ends when it catches a ValueError. Here it is, for what it's worth:
    Code:
    x = "123abc"
    x_number = 0
    for i in xrange(1, len(x)):
        try:
            x_number = int(x[:i])
        except ValueError:
            break
    print x_number
    I also googled for "Python, atoi", and found this archived thread, in which reply #3 has some code that does this too.

    Hope this helps.

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Below are three ways of getting the numbers from a string. The first one gets all the numbers, and the other two get only the leading numbers.[code=Python]x = "123abc456"
      print ''.join([c for c in x if c.isdigit()])

      import re
      patt = re.compile(r'^([0-9]+)')
      print patt.search(x). group(1)

      x_num = ''
      for c in x:
      if c.isdigit():
      x_num += c
      else:
      break
      print x_num[/code]Output:
      >>> 123456
      123
      123

      Comment

      • nicstel
        New Member
        • Jun 2008
        • 20

        #4
        It was exactly what I wanted

        Thank you at both of you

        Comment

        • ghostdog74
          Recognized Expert Contributor
          • Apr 2006
          • 511

          #5
          KISS
          Code:
          >>> import string
          >>> x="abc123"
          >>> x.strip(string.letters)
          '123'
          >>> x="123abc"
          >>> x.strip(string.letters)
          '123'
          >>>

          Comment

          • nicstel
            New Member
            • Jun 2008
            • 20

            #6
            Thank ghostdog74,

            It's more simple. Have a nice day.

            Comment

            Working...