4

I have a list of strings in the format: 'foo7bar'. How is it possible in Python to remove the 7 along with any characters that follow?

This is similar to this question, but I need the answer for Python.

0

1 Answer 1

6

You can do this using Python's slice notation:

>>> mystr = 'foo7bar'
>>> mystr[:mystr.index('7')]
'foo'
>>>

The format for slice notation is [start:stop:step]. The index method of a string finds the position of the first occurrence of its input.

Note however that if you are dealing with something more complex (such as matching patterns), you might want to look into Regular Expressions. For this operation though, the slice notation is sufficient.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.