检查给定对象是否属于给定类型的最佳方法是什么?如何检查对象是否继承给定类型?
假设我有一个对象o.我如何检查它是否是一个str?
我正在编写一个必须接受用户输入的程序.
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
Run Code Online (Sandbox Code Playgroud)
如果用户输入合理数据,这将按预期工作.
C:\Python\Projects> canyouvote.py
Please enter your age: 23
You are able to vote in the United States!
Run Code Online (Sandbox Code Playgroud)
但如果他们犯了错误,那就崩溃了:
C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Traceback (most recent call last):
File "canyouvote.py", line 1, in …Run Code Online (Sandbox Code Playgroud) 有没有办法判断一个字符串是否代表一个整数(例如'3','-17'但不是'3.14'或'asfasfas')没有使用try/except机制?
is_int('3.14') = False
is_int('-7') = True
Run Code Online (Sandbox Code Playgroud) 在下面的代码中为什么x和y字符串而不是整数?网上的所有内容都说要使用raw_input(),但是我读input()了raw_input()在Python 3.x中重命名的Stack Overflow(在一个不处理整数输入的线程上).
play = True
while play:
x = input("Enter a number: ")
y = input("Enter a number: ")
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y)
if input("Play again? ") == "no":
play = False
Run Code Online (Sandbox Code Playgroud) 我有一些Python代码通过一个字符串列表运行,如果可能的话将它们转换为整数或浮点数.对整数执行此操作非常简单
if element.isdigit():
newelement = int(element)
Run Code Online (Sandbox Code Playgroud)
浮点数更难.现在我正在使用partition('.')拆分字符串并检查以确保一侧或两侧是数字.
partition = element.partition('.')
if (partition[0].isdigit() and partition[1] == '.' and partition[2].isdigit())
or (partition[0] == '' and partition[1] == '.' and partition[2].isdigit())
or (partition[0].isdigit() and partition[1] == '.' and partition[2] == ''):
newelement = float(element)
Run Code Online (Sandbox Code Playgroud)
这是有效的,但显然if语句有点像熊.我考虑的另一个解决方案是将转换包装在try/catch块中,看看它是否成功,如本问题所述.
有没有其他想法?关于分区和try/catch方法的相对优点的意见?
我需要更换一些字符如下:&- > \&,#- > \#,...
我编码如下,但我想应该有更好的方法.任何提示?
strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...
Run Code Online (Sandbox Code Playgroud) 如何检查,如果用户的字符串输入是一个数字(例如-1,0,1等)?
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
Run Code Online (Sandbox Code Playgroud)
由于input始终返回字符串,因此上述操作无效.
例如,我想检查一个字符串,如果它不能转换为整数(with int()),我该如何检测?
我想获得键入的完整命令行.
这个:
" ".join(sys.argv[:])
在这里不起作用(删除双引号).此外,我不想重新加入被解析和拆分的东西.
有任何想法吗?
如何使用正则表达式从字符串中提取double值.
import re
pattr = re.compile(???)
x = pattr.match("4.5")
Run Code Online (Sandbox Code Playgroud) python ×10
string ×4
input ×2
int ×2
python-3.x ×2
types ×2
command-line ×1
converter ×1
integer ×1
loops ×1
python-2.7 ×1
regex ×1
replace ×1
user-input ×1
validation ×1