1

I have an entire string in python. I want to isolate part of that which is a number with a decimal and convert into an int. I've searched and tried lots of things including an array but no dice.

#msg.payload is a string of 1:3.45
s = msg.payload
print(msg.payload)

if (s[0] == "1"):
    print("Distance from Anchor 1 received")
    d1 = arr.array((s[2], ".", s[4], s[5]))
    d1converted = int(d1)
    print(d1)

I want to isolate '3.45' from the string '1:3.45' and then convert the '3.45' to an int. I know once you have '3.45' as a string you can simply do int(3.45) to convert it. However, I'm struggling isolating that part of the string with the decimal in the first part. Any help is greatly appreciated!

3 Answers 3

2

If the string you're given is '1:3.45' then you could split the string at the semicolon with python's native .split() method as follows...

string = "1:3.45"
split_string = string.split(":")  # split_string is ["1", "3.45"]
num = split_string[1]

Then like you said, you could make an int with int(float(num)) which will round down, or round(float(num)) in case you would want to round and a later string were "1:3.55"

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response! I'm able to get your code working on an example like "1:3", and I can isolate and print the 3 as an int. But, when I add a decimal to the 3 like "1:3.45", then it doesn't work and won't print anything. The decimal is still throwing it off. Any ideas why? I'm using Python 2.7.13 if that helps at all.
With some more messing around to just isolate the decimal, I was able to finally get there with num = float((s.split(':')[1])) Thanks again!
0

If your input string is in the format of 'int1:int2.int3', you can split first them with : and then take the second part and again split by . like this :

s = '1:3.45'
int1 = int(s.split(':')[0])
int2 = int(s.split(':')[1].split('.')[0])
int3 = int(s.split(':')[1].split('.')[1])

OUTPUT :

int1 = 1
int2 = 3
int3 = 45

Comments

0

Split by ":" which returns an array, convert to float, convert to int:

int(float("1:3.45".split(':')[1]))

1 Comment

Code only answers are not as helpful as those with explanations. Please edit your answer to include additional information, like what this does and why it solves the issue. See How to Answer for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.