dke*_*tre 5 python input code-separation python-3.x
我现在正在编写一个代码,其中一部分需要要求用户在一行中输入 3 个不同的数字(每个数字可以是任意位数)。假设我要求用户输入,他输入:“31 722 9191”。数字之间需要有空格。您将如何分离这些数字并为每个数字分配一个变量。例如 31 是“A”,722 是“B”等等......到目前为止我得到的是:
user_input = input(" Please enter the numbers: ")
Run Code Online (Sandbox Code Playgroud)
谢谢 !
使用拆分和序列拆包的组合。
user_input = user_input(" Please enter the numbers: ")
a, b, c = user_input.split()
Run Code Online (Sandbox Code Playgroud)
split将获取您的数字字符串,例如“xy z”,并将其转换为字符串中的元素列表,其中元素是字符串中以空格分隔的所有单词。因此,split输入“xy z”将产生字符串 ['x', 'y', 'z']。
由于列表是序列的一种形式,因此可以“解包”其元素并将其分配给您选择的变量列表。