3

I have a string which is a combination of "S"s and "C"s. There is at least one occurrence of each.

I want to find the last occurrence of "CS" and change it to "SC".

I have two methods (so far):

P = P[::-1].replace("SC", "CS", 1)[::-1]

and

P = P[:P.rfind("CS")] + "SC" + P[P.rfind("CS") + 2:]

Which line is likely to be faster? Also, is there a quicker way to achieve what I'm doing?

Adi219
  • 4,712
  • 2
  • 20
  • 43
  • You can test this by running both functions times and measuring the time difference between start and end using time.time(). – Nathan Apr 07 '18 at 14:41
  • 1
    You should look into the `timeit` module. If you are working in the iPython console, look into the `%timeit` magic command. You can answer this kind of question ("which line is likely to be faster?") on your own. – Rory Daulton Apr 07 '18 at 14:47

2 Answers2

8

This is one way:

>>> s = 'CSsomethingSCSagainCSsomething'
>>> 'SC'.join(s.rsplit('CS', 1))
CSsomethingSCSagainSCsomething

Syntax:

new_substring.join(str.rsplit(old_substring, occurance))
Austin
  • 25,759
  • 4
  • 25
  • 48
2

In my crude timing, this beats the rsplit() and join() solution by 20%:

head, _, tail = string.rpartition('CS')
new_string = f"{head}SC{tail}"

I does depend on Python 3.6+, of course.

cdlane
  • 40,441
  • 5
  • 32
  • 81