Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i split a string into two on the first occurrence of a character [duplicate]

I have written a code to list all the components in my Linux server. The list is stored in a file. I will ready line by line and have to split the components from version and store in 2 different strings.

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

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

I can see ['console', '3.45.1', '0\r\r'] which is not what I wanted. How can I split into 2 strings on the first occurrence of '-' ?

like image 808
Roshan r Avatar asked Dec 25 '22 16:12

Roshan r


1 Answers

str.split takes a maxsplit argument, pass 1 to only split on 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'
like image 145
Padraic Cunningham Avatar answered Jan 21 '23 14:01

Padraic Cunningham