how can I split a string

Asked by Marc Summers on 2018-05-03

I want to take the output for a screen element like this:

M[1082,813 295x37]@S(S(0)[0,0 1920x1200]) S:1.00 C:1229,831 [-1 msec]

And split it up so I can extract the S:1.00 part.

I tried this:

available = list(findAll("nomoreupdatesavailablethiscycle.png"))
numAvail = len(available)
print numAvail

print available[0]
s=available[0]
a,b,c,d=s.split(" ")
print d

But got this error:

[error] Error caused by: Traceback (most recent call last):
  File line 68, in <module>
    a,b,c,d=s.split(" ")
AttributeError: 'org.sikuli.script.Match' object has no attribute 'split'

Is there some what to either do like a C strstr pattern recognition
or some way to tokenize the string ?

Thanks.

Question information

Language:
English Edit question
Status:
Solved
For:
Sikuli Edit question
Assignee:
No assignee Edit question
Solved by:
Marc Summers
Solved:
2018-05-03
Last query:
2018-05-03
Last reply:
Marc Summers (2aircraft) said : #1

OK I got it to work.
Thanks for the great documentation. :)

image = ["some.png"]
matches = findAnyList(image)
for match in matches:
    print match.getScore()

M[1082,813 295x37]@S(S(0)[0,0 1920x1200]) S:1.00 C:1229,831 [-1 msec]
0.999999642372

Hello Marc.

Your initial problem was that string is needed for string.split to work, and Match type does not convert automatically.
To get string from Match (or any other type) you need str(Match).

Here piece of code working in Sikuli 1.1.1:
____
find("1525525190673.png")
string_result = str(getLastMatch())
array_of_split = string_result.split()
print(array_of_split)
____

But in my opinion this way is not that good for code readability sake.
I had a similar need to extract part of a string recently. Here what I came with:

____
my_string= "Alpha: 0.1674444 Beta: 0.221314"
alpha_string = my_string[my_string.find("Alpha: ") + 7 : my_string.find(" Beta: ")]
print(alpha_string)

# this is working code producing output 0.1674444 in SikuliX 1.1.1
____

Two techniques used here:
1) Python slicing — using some_string[x:y] to get part of string between integer positions x (included) and y (not included)
2) string .find method allowing to find first inclusion of some substring in some big string.

The second piece of code informs that you actually need slice of string between "Alpha:" + some offsent and " Beta: ", what is IMO more convenient.

Hope that helps.

Marc Summers (2aircraft) said : #3

Hello Roman:

Thanks for the help.
I still have a lot to learn when it comes to Python. :)