Forum Archive

Split a string

procryon

Hello all, I have a simple question.

x="Jump Up"

How would I see if first the word Jump is in the string and then see if the word Up is one space after it. Then how could I split the string into two parts ("Jump " and "Up") to use the "Up" string for later use? Thanks :)

Webmaster4o

x.split() will give you each word as an element in a list. So, to get the second word of your sentence, you use x.split()[1].

You could do something like:

words = x.split()
if words[0].lower() == "jump":
    second_word = x.split()[1]
procryon

Thanks!

It works fine, but when I tried to make a different little project with it, an error I can't understand the cause of keeps popping up:


from objc_util import *
import console
UIScreen = ObjCClass('UIScreen')


screen = UIScreen.mainScreen()
x=input()
words=x.split()
if words[0].lower() == "set":
       second_word = x.split()[1]
       float(second_word)
       screen.setBrightness_(second_word)

For this little project, I just want to be able to input some text and check if it says set and has a decimal number (like 0.9) after it. Then I want to convert that 0.9 to a float to be used to set the screen brightness to 0.9. When I tell it to run and type in exactly what's necessary, nothing happens. What could I be doing wrong?

dgelessus

float takes a string, tries to convert it to a float number, and returns that number if successful. If you write

float(second_word)

it converts second_word to a float number, and then throws it away, because you aren't storing the returned value anywhere. You need to write something like

brightness = float(second_word)
screen.setBrightness_(brightness)
Cethric

@procryon: float(second_word) is never stored hence, screen.setBrightness_(second_word) will fail as a str object is being passed as an argument instead of a float or int object.
Hence: float_value = float(second_word) and changing screen_word to float_value in screen.setBrightness_ should resolve your issue.
I agree that ctypes/objc_util errors can sometimes be a little hard to read, however the error type (TypeError, ValueError, etc) can be a hint towards what the issue might be. In this instance passing a str argument where a float or int is expected.

procryon

@Cethric @dgelessus Thanks! I got it to work and understand now!