Python Forum

Full Version: String slicing problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, can someone please help me understand why this code doesn't work?

data = 'XBOX 360 | 150 | NEW'

product = data[data.index('1'):data.index('|')]
product
''
product = data[data.index('1'):data.index('N')]
product
'150 | '
As you can see it works when I index 'N' but not the '|'
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> data = 'XBOX 360 | 150 | NEW'
>>> data.index('|')
9
>>> data.index('1')
11
It's because start index (11) is greater than end index (9)

what do you want to achieve?
First of all, thank you Buran for your fast answer.

I want to slice out 150 without using the index number like this:

product = data[data.index('1'):14]
product
'150'
you can split data at ' | '
>>> data = 'XBOX 360 | 150 | NEW'
>>> data.split(' | ')[1]
'150'
there are also other options, as well as it is possible to use RegEx
That solved the problem!

Thank you very much, I appreciate the help!