如何在Python中获取整数输入的一部分

huangapple go评论64阅读模式
英文:

How to get a part of an integer input in Python

问题

让我们假设我们有一个示例输入23,如何将2单独打印出来,然后将3单独打印出来。

我尝试使用类似chr()的东西,但失败了。

我得到的输入将是棋盘上的坐标。例如,如果输入是23,我想将2作为列和3作为行。因此,我需要拆分输入,以便能够操作代码。

英文:

Let's say we have for example the input 23, how can we print 2 by itself and 3 by itself.

I was trying to use something like chr() but I failed.

I am getting an input that will be the coordinates of a chess board.
For example if the input is 23, I want to have 2 as the column and 3 as the row.
So I need to split the input so that I can manipulate the code.

答案1

得分: 0

如果您的输入值是一个字符串,您可以使用字符串索引来获取每个数字,类似这样:

input_value = '23'

column = int(input_value[0])
row = int(input_value[1])

print('column:', column, ' row:', row)

输出结果:column: 2 row: 3

如果您的输入值是一个整数,您可以首先使用 str() 将其转换为字符串。

英文:

If your input value is a string, you can use string indexing to get each digit,
something like this:

input_value = '23'

column = int(input_value[0])
row = int(input_value[1])

print('column:', column, ' row:', row)

Output: column: 2 row: 3

If your input value is an integer, you can first turn it into a string using str()

答案2

得分: 0

你可以使用map()函数并利用解包:

coord = "23"
col, row = map(int, coord) # col=2 row=3
英文:

you can use map() and leverage unpacking

coord = "23"
col,row = map(int,coord) # col=2 row=3

huangapple
  • 本文由 发表于 2023年8月4日 00:44:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定