1

I'd like to split the below string by only the first equal sign in that string

String:

 s= 'ButtonParams=U3ViamVjdCxFbWFpbA=='

Desired_String:

 s= ['ButtonParams','U3ViamVjdCxFbWFpbA==']

When I do s.split("="), I get the following, which is what I do not want:

s.split("=")
['ButtonParams', 'U3ViamVjdCxFbWFpbA', '', '']

I need to run this function across a list of strings where this is the case, so scalability is important here.

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
Chris
  • 4,866
  • 13
  • 58
  • 110

3 Answers3

8

split accepts an optional "maxsplit" parameter: if you set it to 1 it will split on the first = character it finds and return the remainder of the string:

>>> s.split('=', 1)
['ButtonParams', 'U3ViamVjdCxFbWFpbA==']
Alex Riley
  • 152,205
  • 43
  • 245
  • 225
3

s.split("=", maxsplit=1) is the best but

import re
print (re.split('=',s,1))

The output is

['ButtonParams', 'U3ViamVjdCxFbWFpbA==']

As you have tagged

A little deviation from the post

If the expected output was ['ButtonParams', 'U3ViamVjdCxFbWFpbA'] then you can have the following liscos (list comprehensions)

  • [i for i in s.split('=') if i is not '']
  • [i for i in s.split('=') if i ] (Contributed by Adam Smith)
Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
1

str.split accepts an optional argument maxsplit which determines how many splits (maximally) to make, e.g.:

"ButtonParams=U3ViamVjdCxFbWFpbA==".split("=", maxsplit=1)
# ['ButtonParams', 'U3ViamVjdCxFbWFpbA==']
Adam Smith
  • 48,602
  • 11
  • 68
  • 105