String slicing problem - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: String slicing problem (/thread-12701.html) |
String slicing problem - Ollew - Sep-08-2018 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 '|' RE: String slicing problem - buran - Sep-08-2018 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') 11It's because start index (11) is greater than end index (9) what do you want to achieve? RE: String slicing problem - Ollew - Sep-08-2018 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' RE: String slicing problem - buran - Sep-08-2018 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 RE: String slicing problem - Ollew - Sep-08-2018 That solved the problem! Thank you very much, I appreciate the help! |