int input

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • oursmokeingjoe
    New Member
    • Mar 2008
    • 3

    int input

    sorry but this is probably a stupid question but;
    if you have an input like
    pos = 'c3'
    #and you want to take out the second character as an int what do you need to add to stop it from producing an error if the second character is a letter
    eg. pos = 'cd'
    # i've been using
    int(pos[1]) # but it gives an error when the [1] is a letter not a number.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by oursmokeingjoe
    sorry but this is probably a stupid question but;
    if you have an input like
    pos = 'c3'
    #and you want to take out the second character as an int what do you need to add to stop it from producing an error if the second character is a letter
    eg. pos = 'cd'
    # i've been using
    int(pos[1]) # but it gives an error when the [1] is a letter not a number.
    Following are a couple of ways.[code=Python]
    >>> pos = 'cd'
    >>> digits = '0123456789'
    >>> if pos[1] in digits:
    ... print "It's a digit!"
    ... else:
    ... print "It's no digit!"
    ...
    It's no digit!
    >>> pos = 'c4'
    >>> if pos[1] in digits:
    ... print "It's a digit!"
    ... else:
    ... print "It's no digit!"
    ...
    It's a digit!
    >>> try:
    ... col = int(pos[1])
    ... except:
    ... col = pos[1]
    ...
    >>> col
    4
    >>> pos = 'cd'
    >>> try:
    ... col = int(pos[1])
    ... except:
    ... col = pos[1]
    ...
    >>> col
    'd'
    >>> [/code]

    Comment

    • oursmokeingjoe
      New Member
      • Mar 2008
      • 3

      #3
      # heres the problem how can i manipulate just row = to get the aproiate response
      position = 'cd'
      col = position[0]
      row = int(position[1])
      if col in ['a','A','b','B' ,'c','C','d','D ','e','E','f',' F','g','G','h', 'H'] and row in [1,2,3,4,5,6,7,8]:
      print 'The piece is moved to %s%s.' % (col,row)
      elif col not in ['a','A','b','B' ,'c','C','d','D ','e','E','f',' F','g','G','h', 'H'] and row in [1,2,3,4,5,6,7,8]:
      print 'The first coordinate is not in the range a-h or A-H!'
      elif col in ['a','A','b','B' ,'c','C','d','D ','e','E','f',' F','g','G','h', 'H'] and row not in [1,2,3,4,5,6,7,8]:
      print 'The second coordinate is not in the range 1 to 8!'
      else:
      print 'The column value and row value is not in the ranges a-h, A-H and 1 to 8!'

      Comment

      • Smygis
        New Member
        • Jun 2007
        • 126

        #4
        Why not use the built in stuff that whas ment for this...

        [code=python]
        >>> pos = "cd"
        >>> pos[1].isdigit()
        False
        >>> pos[1].isalpha()
        True
        >>> pos = "c1"
        >>> pos[1].isdigit()
        True
        >>> pos[1].isalpha()
        False
        >>>
        [/code]

        Comment

        Working...