0

This is driving me crazy. I have a string like this:

Sheridan School III

In a list like this:

Sheridan School III
Lake Bluff Elementary II
Barrington IV

I'd like to make the trailing portion into a variable homeseries

And make the portion that precedes that into variable homeclub

When I split the string I can get the series, no problem, as in below.

But I cannot use that series inside the .replace string, where I'd like to just use it to get rid of the last part of the original string. How do I use a variable inside .replace? Python throws an error and I'm sure there is a simple way to reference this as a variable.

homeclubfull = "Sheridan School III"
homeclublist = homeclubfull.split(" ")
homeseries = homeclublist[-1:]    # this should return "III"
homeclub=homeclubfull.replace(homeseries,'')
print homeclub, home series

error thrown:

import.py:51: TypeError: expected a character buffer object

2 Answers 2

2

Split from the end with the str.rsplit() method and a limit:

homeclub, homeseries = homeclubfull.rsplit(None, 1)

Demo:

>>> homeclubfull = "Sheridan School III"
>>> homeclub, homeseries = homeclubfull.rsplit(None, 1)
>>> homeclub
'Sheridan School'
>>> homeseries
'III'

The error you get because you were trying to pass a list to .replace(), not a string; you wanted this instead:

homeseries = homeclublist[-1]   # Note, no : 

You were slicing the list, not selecting one element. Slicing results in a list, always:

>>> homeclubfull.split()[-1:]
['III']
>>> homeclubfull.split()[-1]
'III'
Sign up to request clarification or add additional context in comments.

1 Comment

Not only did you fix it (thanks) you educated me (thanks ^2)- you're fantastic, Martijn!!
0

Your problem would be solved if instead of homeclublist[-1:] you used homeclublist[-1] because the first one returns a list (it leaves a trailing space that you can strip).

You could also do this without replace; by slicing the part of the list that you want as opposed to the part that you don't want and then replace:

homeclubfull = "Sheridan School III"
homeclublist = homeclubfull.split()
homeseries = ' '.join(homeclublist[:-1])
print(homeseries)

1 Comment

Thanks, Jurgenreza -- appreciate the clarification!!

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.