Reputation: 2582
I want to export and use numbers in a string in Python 3.
for example
_input = input()
>? circle(5)
I want to export and use 5 as float here.
I tried to use _input.split('circle(') but it makes a list with 2 elements ['', '5)'] I tried to use _input.split(')') an, it makes another list with 2 elemtens ['circle(5', '']
Is there any module that helps me to do it or I should use split in another way ?
After this, what if I want to use 2 numbers ?
for example
_input = input()
>? circle(5,3.14)
or
_input = input()
>? circle(5, 3.14)
and then multiply this numbers ( 5 * 3.14 )
Upvotes: 2
Views: 139
Reputation: 2584
If there will be just one function with brackets then use this. First we extract string inside the bracket. Now it'll be easy for us to do whatever we want with the string.
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])
String in brack function taken from here. What you do is you first search for the opening bracket '(' and then you slice the string till where the closing bracket is found ie ')'. Suppose string is s='blahblah'
then s[4:7]
will return 'bla' etc..
Upvotes: 1
Reputation: 78790
Hardcode-y way to parse your string:
>>> s = 'circle(5, 3.14)'
>>> a, b = map(float, s.strip()[7:-1].split(','))
>>> a
5.0
>>> b
3.14
>>> a*b
15.700000000000001
i.e. take the number part, split by comma, turn the list elements to floats and multiply them.
Using a regex might be more easily translatable to similar problems:
>>> import re
>>> s = 'circle(5, 3.14)'
>>> a, b = re.match('\s*circle\((\d(?:\.\d+)?),\s*(\d(?:\.\d+))?\)\s*', s).groups()
>>> float(a)*float(b)
15.700000000000001
regex101 demo: https://regex101.com/r/O3bSwr/1/
Upvotes: 1
Reputation: 1624
Probably regular expressions is the best alternative
import re
input_ = 'circle(5, 3.14)'
numbers = re.findall('\\d+[.]*\\d*', input_)
float(numbers[0]) * float(numbers[1])
Upvotes: 1