0

I'm looking for a way in Python to change, for example, the string "Main St & 1st St" into the string "1st St & Main St".

I know I could do something to the effect of:

intersection = "Main St & 1st St"
intersectionList = intersection.split(" & ")
reversedIntersection = (" & ".join(intersectionList[::-1])).strip()

But it just seems needlessly multi-stepped and I was wondering if there was a more efficient method, a built-in method, etc... that could accomplish the same goal better.

6
  • 3
    reversedIntersection = (" & ".join(intersection.split(" & ")[::-1])).strip(). There, now you have it in one step. Commented Apr 29, 2015 at 16:29
  • '&'.join(list(reversed(s.split('&')))) Commented Apr 29, 2015 at 16:31
  • @ChinmayKanchi, you're halfway there. The result should be a string, not a list. Commented Apr 29, 2015 at 16:31
  • @Kevin this should be an answer, not a comment. Commented Apr 29, 2015 at 16:35
  • 1
    @ChinmayKanchi you don't need list(), reversed() already returns a list Commented Apr 29, 2015 at 17:13

2 Answers 2

2
original[original.find(" & ")+3:]+ " & " +original[:original.find(" & ")]

>>> original  = "Main St & 1st St"
>>> original.find(" & ")
7
>>> original[:original.find(" & ")]
'Main St'
>>> original[original.find(" & ")+3:]
'1st St'
>>> original[original.find(" & ")+3:]+ " & " +original[:original.find(" & ")]
'1st St & Main St'

or make a function

>>> def new(s):
...     x = " & "
...     if x not in s: return s 
...     else:
...             return s[s.find(x)+3:]+x+s[:s.find(x)]
... 
>>> new(original)
'1st St & Main St'
>>> new("2nd ave. & 6th st.")
'6th st. & 2nd ave.'
Sign up to request clarification or add additional context in comments.

Comments

1

I don't think your way is to multi-stepped. The shortest way I can find to describe what you want to do is:

  1. take a string

  2. split it at the ampersands

  3. reverse the substrings

  4. write down the substrings, separating them by ampersands

That's exactly what you code does. If you want you code to be more compact, you can leave the .strip() at the end since it isn't really useful and rewrite the 2nd and 3rd lines like this:

reversedIntersection = (" & ".join(intersection.split(" & ")[::-1]))

I don't know of any built-in method for this, since you can code it with roughly the same work it takes you to describe it and it isn't a common problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.