0

I want to input a vector in the form "(x,y,z)"

    s=raw_input("Enter vector (x,y,z): ")
    x,y,z= s.split()
    self.x= float(x)
    self.y= float(y)
    self.z= float(z)

What is missing in the code? Shouldn't split do the job?

I tried s.split("(",",",")") also, but with no success.

3 Answers 3

4

You can use ast.literal_eval for such input:

>>> import ast
>>> s = "(1,100,200)"
>>> x, y, z =  ast.literal_eval(s)
>>> type(x)
<class 'int'>

Using string functions you need to strip () first and then split on ,:

>>> x, y, z = s.strip('()').split(',')
>>> x, y, z
('1', '100', '200')

Help on str.split:

S.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

Sign up to request clarification or add additional context in comments.

Comments

1

If you are inputting like this:

Enter vector (x,y,z):
> 2,3,4

You'd want to do

x, y, z = s.split(",")

If you're inputting the numbers seperated by comma and space, do this:

x, y, z = s.split(", ")

str.split splits the string into substrings, split on each occurence of the argument supplied (which defaults to " ").

Comments

1

An alternative: capture what you want rather than splitting-away what you don't.

import re
s = '(44.2, 19, 12.73)'
floats_rgx = re.compile(r'-?\d+(?:\.\d+)?')
x, y, z = map(float, floats_rgx.findall(s))

That approach has the advantage (or disadvantage, depending on your goals) of allowing more open-ended input formats. If you want something more strict, you could write a complete regular expression to validate the precise input format.

1 Comment

Might want to also add -? to the start of the pattern to handle negative numbers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.