简体   繁体   English

Python 3在输入中采用多种数据类型,以空格分隔

[英]Python 3 taking multiple data types in input, separated by space

So i need to find a way to take multiple data types as an input and store them in variables. 所以我需要找到一种方法来将多种数据类型作为输入并将它们存储在变量中。 Lets say i have 3 variables, each of them should store a fixed data type a - float b - str c - int 可以说我有3个变量,每个变量都应存储一个固定的数据类型a-浮动b-str c-int

and if the user enters a wrong, he will be asked to type again. 如果用户输入错误,将要求他再次输入。 The user will enter all of them, separated by space but i can't think of a way to store them in the variables, while keeping the data type. 用户将输入所有它们,并用空格隔开,但是我想不出一种在保留数据类型的同时将它们存储在变量中的方法。 I've tried with .split(), but it just transforms them into strings. 我已经尝试过.split(),但是它只是将它们转换为字符串。 It's probably something quite obvious, but can't figure it out right now. 这可能很明显,但现在无法解决。 Thanks in advance! 提前致谢!

Maybe: 也许:

def myfucn(vars):
    vars = vars.split()
    try:
        float(vars[0])
        if not "." in vars[0]:
            raise Exception("First var should be INT not Float")
    except ValueError:
        print("Error not Float found")

    try:
        int(vars[2])
    except ValueError:
        print("Error Int no found")

    #answer
    a_float, b_str, c_int = vars
    print(" Yes ")

greetings 问候

You are on the right track if the split() function. 如果使用split()函数,您将走在正确的轨道上。 The problem is that when you say that user will give three values separated by ' ', you are taking in a string. 问题是,当您说用户将给出三个用'分隔的值时,您正在输入一个字符串。 The following is a string: '34.44 35.45 5' Maybe what you can do is after using split, you can cast each returned item to a variable. 下面是一个字符串:'34 .44 35.45 5'也许您可以做的是使用split之后,可以将每个返回的项目强制转换为变量。 If you still need to check the type of variable, you can use the type() function. 如果仍然需要检查变量的类型,则可以使用type()函数。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM