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
  • 50,140
  • 28
  • 121
  • 140
Chris
  • 5,444
  • 16
  • 63
  • 119

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
  • 169,130
  • 45
  • 262
  • 238
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
  • 50,140
  • 28
  • 121
  • 140
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
  • 52,157
  • 12
  • 73
  • 112