如何在python语言中将输入字符串拆分成单独的可用整数
问题描述
我尝试将输入字符串xyz拆分成3个标记,然后再拆分成3个整数,分别称为x、y和z。
我希望它这样做,这样我就可以进行更少的输入,然后能够将它们用于mc.setblocks(x1, y1, z1, x, y, z, BlockId)
的坐标。我如何将它分开,以使它变成3个不同的整数,或者将它们分割成标记来做到这一点?我知道如何在Java中做到这一点,但我不知道如何在Python中做到这一点。它应该如下所示:
xyz1 = input("enter first coordinates example: 102 36 74")
st = StringTokenizer(xyz1)
x = st.nextToken
y = st.nextToken
z = st.nextToken
解决方案
我试着写这篇文章,这样你就能看到发生了什么:
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")
如果只输入了三个以上的坐标,则应将输入标记化并在其上循环,将每个标记转换为int并将其附加到列表中:
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
有趣的是,您可以在主要的一行程序中完成上述操作。这是一种更具蟒蛇风格的方式,因此您可以将其与上面的方式进行对比,以了解其含义:
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
相关文章