TheLittleCoder TheLittleCoder - 3 months ago 18
Python Question

How do I split an input String into seperate usable integers in python

I'm trying to split a Input String xyz into 3 tokens and then seperating into 3 integers called x, y, and z.
I want it to do this so that I have to do less input and then be able to use them for the coordinates of

mc.setblocks(x1, y1, z1, x, y, z, BlockId)
. How do I Separate it so that it turns out as 3 different ints and\or split them into tokens to do so? I know how I would do this in java but I have no clue of how to do it in python. It should look something like this :

xyz1 = input("enter first coordinates example: 102 36 74")
st = StringTokenizer(xyz1)
x = st.nextToken
y = st.nextToken
z = st.nextToken

Answer

I tried writing this less "pythonically" so you can see what's happening:

xyz1 = input("Enter first 3 coordinates (example: 102 36 74): ")

tokens = xyz1.split() # returns a list (ArrayList) of tokenized values
try:
    x = int(tokens[0])   # sets x,y,z to the first three tokens
    y = int(tokens[1])
    z = int(tokens[2])
except IndexError:       # if 0,1,2 are out of bounds
    print("You must enter 3 values")
except ValueError:       # if the entered number was of invalid int format
    print("Invalid integer format")

If you have more than just three coordinates being entered, you would tokenize the input and loop over it, converting each token into an int and appending it to a list:

xyz1 = input("Enter first 3 coordinates (example: 102 36 74): ")

tokens = xyz1.split() # returns a list (ArrayList) of tokenized values
coords = []     # initialise empty list
for tkn in tokens:
    try:
        coords.append(int(tkn))     # convert token to int
    except ValueError:       # if the entered number was of invalid int format
        print("Invalid integer format: {}".format(tkn))
        raise
print(coords)   # coords is now a list of integers that were entered

Fun fact, you can do the above in a mostly one-liner. This is a more pythonic way so you can contrast this with the above to get a sense of what that means:

try:
    xyz1 = input("Enter first 3 coordinates (example: 102 36 74): ")
    coords = [int(tkn) for tkn in xyz1.split()]
except ValueError:       # if the entered number was of invalid int format
    print("Invalid integer format: {}".format(tkn))
    raise