-1

I'm new to Python, and want to make sure I'm doing this the most Pythonic way.

I have a string with a form of something like this:

VAR=(X=Y)

And I need everything to the right of the first = (including any and all subsequent =).

Since rsplit() works right to left, this is how I did it:

definition=line[::-1].rsplit('=', 1)[0][::-]

I reverse it, then split it on the =, take the first element of that split (everything to the left of the last =, or everything to the right of the first = in the unreversed string), then reverse it to get it forward again.

Is there a better, or more idiomatic, way to do this?

Azor Ahai -him-
  • 123
  • 1
  • 7

2 Answers2

3

The best way is to use split with the second parameter.

>>> help(''.split)
Help on built-in function split:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.

>>>

So You can split like the below and then ignore the zeroth index and take the first index.

>>> "VAR=(X=Y)".split('=',1)
['VAR', '(X=Y)']
>>>

Another way to do split is:

>>>
>>> import re
>>> re.split('=', 'VAR=(X=Y)', 1)
['VAR', '(X=Y)']
>>>
kvivek
  • 3,321
  • 1
  • 15
  • 17
2

How about partition:

>>> s = "VAR=(X=Y)"
>>> s.partition("=")
('VAR', '=', '(X=Y)')
>>> s.partition("=")[2]
'(X=Y)'

Or, if you're really dead-set on just using split and variants thereof,

>>> s.split("=",1)[1]
'(X=Y)'
Kevin
  • 74,910
  • 12
  • 133
  • 166