def name_hi(x):
if type(x)!= <type 'str'> :
print "Invaild answer,Try again"
else:
print "Hello"+ x
name_hi(raw_input("what's your name?"))
如何确保我得到的答案是字符串?
答案 0 :(得分:6)
您正在寻找:
if type(x) == str:
或者,更好的是:
if isinstance(x, str):
那就是说,raw_input()
只会返回一个字符串。它不会返回任何其他内容。
由于您正在尝试检查字符串是否只包含字母,因此您应该拨打isalpha()
:
if x.isalpha():
整合:
def name_hi(x):
if x.isalpha():
print "Hello, " + x + "."
else:
print "Invalid answer; try again."
name_hi(raw_input("What's your name?"))
答案 1 :(得分:0)
你想要isinstance()
def check(x)
return isinstance(x, str)
答案 2 :(得分:0)
检查类型是否脆弱。只是尝试做你想做的事情并看看它是否有效可能会更好:
Dim TextSearch As String =
"PrinterName : PDFCreator()" + vbCrLf +
"PortName: PDFCreator()" + vbCrLf +
"Status: Unknown()" + vbCrLf +
"DriverName: PDFCreator()" + vbCrLf +
"PrinterName: Lexmark E360dn XL" + vbCrLf +
"PortName: someport()" + vbCrLf +
"Status: Unknown()" + vbCrLf +
"DriverName: Lexmark E360dn XL" + vbCrLf +
"HostAddress: somehostaddress()"
Dim printers = From printer In TextSearch.Split(vbCrLf.ToCharArray)
Where printer.ToLower.StartsWith("printername")
Select printer.Split(":").Last
For Each printer As String In printers
Debug.Print(printer)
Next
那样:
def name_hi(x):
try:
print "Hello"+ x
except TypeError:
print "Invaild answer,Try again"