Grabbing 1 Value From a Long Strin

So I am reading in a value from a scale head that is set to continuously output. Right now I have a button that says when to grab a value from the scale. The only problem is that it gives me a long list of what appears to be every value since the last time I pressed the button. For example, I would get something like:

17.9 lbG
18.6 lbG
19.2 lbG
19.2 lbG
19.2 lbG
And this could go on for 20 or so more values.

The scripting I have on my button is as follows:
reading = event.source.parent.getComponent(‘ScaleReadIn’)
weight = reading.readString()
print weight

I’m wondering what’s the best way to go about grabbing the very last value? I would use a .split() script but it seems that wouldn’t work if I don’t know how many values there will be. I was thinking about adding all the values to a list and then using something like list[-1]. Does this sound plausible or is there an easier way of going about it?

Split() creates a list, so

lastVal = weight.split("\n")[-1]

should work fine.

2 Likes

In python you can get the last few characters from a string using this syntax:

mystring = "i want to get only the last part"
substring = mystring[-4:]
print substring
#output > "part"

Good to know. My only problem here would be when a weight goes from, say, 99 lbs to 105 lbs. It would leave off the ‘1’ correct?

Ah right, So @mrogers 's solution is better :slight_smile:

Thank you for the quick response. So where am I going wrong here? This is what I’ve got and I’m just getting a blank output.

reading = event.source.parent.getComponent(‘ScaleReadIn’)
weight = reading.readString()

finalWeight = weight.split(“G”)[-1]

print finalWeight

Edit: i figured it out. The last line should be
print finalWeight[-1]

instead of the [-1] where I originally had it. Thanks for your help.

1 Like

Is it possible weight is blank?

Tip: put triple reverse quote / grave marks (often to left of “1” on keyboard) before and after code to make it easy to read on forum.

Thanks for the tip. I was wondering how to do that.

1 Like