Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
String slicing problem
#1
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 '|'
Reply
#2
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?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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'
Reply
#4
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
That solved the problem!

Thank you very much, I appreciate the help!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  f string concatenation problem growSeb 3 537 Jun-28-2021, 05:00 AM
Last Post: buran
Question Problem with string and \n Falassion 6 654 Jun-15-2021, 03:59 PM
Last Post: Falassion
  how to deal with problem of converting string to int usthbstar 1 667 Jan-05-2021, 01:33 PM
Last Post: perfringo
  string problem Mathisdlg 6 1,295 Aug-05-2020, 09:31 AM
Last Post: Mathisdlg
  String slicing and loop iteration divyansh 9 2,182 Jun-07-2020, 10:29 PM
Last Post: divyansh
  String slicing divyansh 6 1,315 May-31-2020, 06:15 AM
Last Post: pyzyx3qwerty
  sequence slicing problem qliu 4 849 Apr-27-2020, 09:50 PM
Last Post: deanhystad
  string slicing help oli_action 2 877 Mar-22-2020, 09:57 AM
Last Post: oli_action
  Unicode string index problem luoheng 6 1,243 Nov-23-2019, 03:04 PM
Last Post: luoheng
  Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) Drone4four 4 1,412 Aug-23-2019, 07:59 PM
Last Post: Drone4four

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020