2

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 )

DarkSuniuM
  • 2,523
  • 2
  • 26
  • 43
  • 1
    Maybe it's because I'm tired. But I don't follow at all what you're trying to do. – vallentin Apr 11 '17 at 08:51
  • @Vallentin Im trying to make a shape calculator, I want user enter the shape name and numbers like this – DarkSuniuM Apr 11 '17 at 08:55
  • If you want to create some sort of calculator, you'll either need a syntax parser (not so easy) or somehow implement this with `eval` (might be simpler but less clean) – Elmar Peise Apr 11 '17 at 09:00

3 Answers3

1

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])
spadarian
  • 1,604
  • 10
  • 14
1

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..

Community
  • 1
  • 1
Abhishek J
  • 2,386
  • 2
  • 21
  • 22
1

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/

timgeb
  • 76,762
  • 20
  • 123
  • 145