Home > Enterprise >  Python - split value to two integers
Python - split value to two integers

Time:03-02

What is the most optimal way to split this key/value of dictionary:

test_status: "2200/2204(99%)"

so that I get two keys whose values are integers:

test_status_excpected: 2204
test_status_got: 2200

CodePudding user response:

Split using / and ( as separators.

The first value is what is left of /

The second value is what is right of / and left of (

Then cast the result into an int

myDict["test_status_excpected"] = int(myDict["test_status"].split("/")[0])
myDict["test_status_got"] = int(myDict["test_status"].split("/")[1].split("(")[0])

CodePudding user response:

pair = {'test_status': '2200/2204(99%)'}

for key, value in pair.items():
    value = value[:9] # this will keep first 9 char which drops (99%) part
    years = value.split("/")
    new_pair = {
        "test_status_excpected": years[1],
        "test_status_got": years[0]
    }

print(new_pair)
# output: {'test_status_excpected': '2204', 'test_status_got': '2200'}

CodePudding user response:

You can use the re module. For example:

import re
test_status = "2200/2204(99%)"
m = re.findall('\d ', test_status)
print(m[0], m[1])

Output:

2200 2204

Note:

This code implicitly assumes that at least two sequences of digits will be found in the string

CodePudding user response:

Split the string using index.

test_status_expected = dic_name["test_status"][:4]
test_status_got = dic_name["test_status"][5:9]

If you are not sure about the index, you can use like:

test_status_expected = dic_name["test_status"][:dic_name["test_status"].index("/")]
test_status_got = dic_name["test_status"][dic_name["test_status"].index("/") 1:dic_name["test_status"].index("(")]
  • Related