Posted By: Anonymous
I am trying to split this string in python:
I want to split that string on the underscore
_ so that I can use the value on the left side.
"2.7.0_bf4fda703454".split("_") gives a list of strings:
In : "2.7.0_bf4fda703454".split("_") Out: ['2.7.0', 'bf4fda703454']
This splits the string at every underscore. If you want it to stop after the first split, use
If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:
In : lhs, rhs = "2.7.0_bf4fda703454".split("_", 1) In : lhs Out: '2.7.0' In : rhs Out: 'bf4fda703454'
An alternative is to use
partition(). The usage is similar to the last example, except that it returns three components instead of two. The principal advantage is that this method doesn’t fail if the string doesn’t contain the separator.