简体   繁体   English

Python自动转换为文本

[英]Python automatically converts to text

I want to get the output if the input value type is "Int" then print this message "please enter the string not integer" else calling the function. 如果输入值类型为“ Int”,我想获取输出,然后打印此消息“请输入字符串而不是整数”,否则调用该函数。

It seems Python automatically takes the value type as "String". 看来Python会自动将值类型设为“字符串”。 But I want to get the message like I mentioned if enter type. 但是我想得到像输入类型一样的消息。 Please check the below code. 请检查以下代码。

def strlength (string):
    lengthstring = len(string)
    return (lengthstring)

string = input("enter the string: ")
if type(string) == int:
    print("please enter the string not integer")
else:
    print(strlength(string))

Thank you in advance 先感谢您

It seems Python automatically takes the value type as "String" 看来Python会自动将值类型设为“字符串”

No. The value type is string, until you convert it to something else. 不会 。值类型字符串,直到将其转换为其他类型为止。 There is no secret magic that guesses possible variable types from the user's input. 没有秘密的魔术可以从用户的输入中猜测可能的变量类型。

There is a helper function isdigit you can use to check if a string only consists of digits. 有一个辅助函数isdigit ,可用于检查字符串是否仅由数字组成。

response = input("enter the string: ")

if str.isdigit(response):
    ...

this is your solution 这是你的解决方案

 def strlength (string):
    lengthstring = len(string)
    return (lengthstring)

string = input("enter the string: ")

try:
    string = int(string)
    print("please enter the string not integer")
except :
    print(strlength(string))

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

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