2

I want to parse a string in python. Example string is four numeric values separated by white spaces. I want to parse and turn into them floating point values. The code I'm dealing is below. When I debug the code. It never enters into the else block? what's the missing point?

def stringToQuaternion(self, str):
        s = ''
        list = []
        for i in range (0, len(str)):
            if ( str[i] != string.whitespace ):
                s += str[i]
            else:
                list.append(float(s))
                s = ''
        return Quadro(list[0], list[1], list[2], list[3])

3 Answers 3

7

"If it's hard, you're doing it wrong." ­—me

Quadro(*[float(x) for x in S.split()])
Sign up to request clarification or add additional context in comments.

Comments

2

You are comparing str[i], which is a single character, to string.whitespace, which consists of several characters. This means str[i] and string.whitespace can never be equal.

You could use str[i] in string.whitespace or even better str[i].isspace() instead.

(As a side note, don't name a variable str in Python, since this will shadow the name of the built-in type.)

Comments

0

You probably want str[i] in string.whitespace rather than !=. However, an explicit loop like this is not very Pythonic. Try this more idiomatic approach:

def stringToQuaternion(self, s):
    l = [float(w) for w in s.split()]
    return Quadro(l[0], l[1], l[2], l[3])

(It's best not to use str and list as variable names as those are built-in data types.)

The syntax func(*l) unpacks the items in a list l and passes them as individual arguments to a function. Even simpler, if a bit more cryptic:

def stringToQuaternion(self, s):
    return Quadro(*[float(w) for w in s.split()])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.