Stark Shaw
Stark Shaw

Reputation: 21

Get the index of a character or a substring by reversely loop in Python

Here is what I want to do in Java, however I need to implement this into Python.

String foo = new String("Foo's bar");
for (int i = foo.length-1; i--; i>=0) {
    if(foo[i] == '\'') {
        String bar = foo.substring(0,i);
    }
}

What I want to do is find a key character from the last character to the very first one once I find it I need to substring the rest part (Imagine get someone's name from a phrase).

Upvotes: 0

Views: 58

Answers (2)

Ahasanul Haque
Ahasanul Haque

Reputation: 11144

What you want to achieve is quite easy. You will get a list of splited elements. Pick the first one.

"Foo's bar".split("\'")[0]

Upvotes: 2

Dušan Maďar
Dušan Maďar

Reputation: 9909

Try rfind(): https://docs.python.org/2/library/stdtypes.html#str.rfind

foo = "Foo's bar'"
index_to = foo.rfind("'", 0, len(foo))
print foo[0:index_to]
>>> Foo

Upvotes: 2

Related Questions