Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Split a string
-
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 :)
-
x.split()
will give you each word as an element in a list. So, to get the second word of your sentence, you usex.split()[1]
.You could do something like:
words = x.split() if words[0].lower() == "jump": second_word = x.split()[1]
-
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?
-
float
takes a string, tries to convert it to a float number, and returns that number if successful. If you writefloat(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 likebrightness = float(second_word) screen.setBrightness_(brightness)
-
@procryon:
float(second_word)
is never stored hence,screen.setBrightness_(second_word)
will fail as astr
object is being passed as an argument instead of afloat
orint
object.
Hence:float_value = float(second_word)
and changingscreen_word
tofloat_value
inscreen.setBrightness_
should resolve your issue.
I agree thatctypes
/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 astr
argument where afloat
orint
is expected. -
@Cethric @dgelessus Thanks! I got it to work and understand now!