我想在 Python 3 中导出并使用字符串中的数字。
例如
_input = input()
>? circle(5)
我想在这里导出并使用 5 作为 float 。
我尝试使用 _input.split('circle(') 但它创建了一个包含 2 个元素的列表 ['', '5)'] 我尝试使用 _input.split(')') ,它用 2 个元素创建另一个列表 ['circle(5', '']
是否有任何模块可以帮助我做到这一点,或者我应该以其他方式使用 split ?
此后,如果我想使用 2 个数字怎么办?
例如
_input = input()
>? circle(5,3.14)
或
_input = input()
>? circle(5, 3.14)
然后将这个数字相乘 ( 5 * 3.14 )
最佳答案
如果只有一个带括号的函数,则使用它。首先我们提取括号内的字符串。现在我们可以轻松地对字符串执行任何我们想要的操作。
s=input()
string_in_brack = s[s.find("(")+1:s.find(")")]
numbers = string_in_brack.split(',')
if len(numbers)>1:
float(numbers[0]*numbers[1])
else:
float(numbers[0])
括号函数中的字符串取自 here 。您要做的就是首先搜索左括号“(”,然后对字符串进行切片,直到找到右括号,即“)”。假设字符串是 s='blahblah'
那么 s[4:7]
将返回 'bla' 等..
关于python - 在字符串输入中使用数字,Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43341035/