How do I split an input String into seperate usable integers in python(如何在python语言中将输入字符串拆分成单独的可用整数)
本文介绍了如何在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
这篇关于如何在python语言中将输入字符串拆分成单独的可用整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何在python语言中将输入字符串拆分成单独的可用整数


基础教程推荐
猜你喜欢
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01