5

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 '-' ?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Roshan r
  • 522
  • 2
  • 11
  • 30

1 Answers1

11

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'
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321