How can I split a string in two on the first occurrence of a character

I wrote some code to list all the components on my Linux server. The list is stored in a file. I will be ready in turn and have to split the components from version and save on 2 different lines.

For example, one of my lines shows console-3.45.1-0 where console is the component and version 3.45.1-0 is the version. If I use split,

print components[i].split('-')

      

I see ['console', '3.45.1', '0\r\r']

what I didn't want. How can I split into 2 lines on the first occurrence of '-'?

+3


source to share


1 answer


str.split takes a maxsplit argument, passes 1 to split by only the first -

:

print components[i].rstrip().split('-',1)

      



To store the output in two variables:

In [7]: s = "console-3.45.1-0"

In [8]: a,b = s.split("-",1)

In [9]: a
Out[9]: 'console'

In [10]: b
Out[10]: '3.45.1-0'

      

+9


source







All Articles