fdama
fdama

Reputation: 304

Issue with Slicing in Python

I'm new to python and I am currently working on a exercise that involves slicing. The exercise involves slicing the string 'Pizza' in any way. You enter the starting and ending positions of the slice and the program displays the results. Here is my code:

    #Pizza Slicer

print(
"""
  Slicing 'Cheat Sheet'

 0   1   2   3   4   5
 +---+---+---+---+---+ 
 | p | i | z | z | a | 
 +---+---+---+---+---+ 
-5  -4  -3  -2  -1

"""
)

word="pizza"

print("Enter the beginning and ending index for your slice of 'pizza'.")
print("Press the enter key at 'Begin' to exit.")

start=None      #initialise  
while start !="":  
    start=int(input("\nStart: "))

    if start:

        finish=int(input("Finish: "))

        print("word[",start,":",finish,"] is", word[start:finish])

The issue is that when I enter a starting value of '0' I cannot enter a finishing value - 'Start:' appears again. I think this may have something to do with the 'Start = None' statement. The other issue is that entering negative starting and ending values does not work and will not return the slice. Not sure why.

Thanks for your assistance.

Upvotes: 0

Views: 429

Answers (3)

Ankur Agarwal
Ankur Agarwal

Reputation: 24778

If you want to learn more about python slicing check this out:

The python slice notation

Upvotes: 0

Bryan
Bryan

Reputation: 2088

You are correct that the error is most likely due to start != "" since both an empty string and 0 evaluate to false. perhaps you could use pythons built in isinstance like so:

if isinstance(start,int):
    #do something

However, this will accept any integer which could cause problems if someone enters a number outside of the range -5 to 5. Instead you you could use range to set the acceptable values:

if start in range(-5,6):
   #do something

Upvotes: 0

falsetru
falsetru

Reputation: 369424

The issue

If 0 is used as predicate, it is treated as False.

>>> if 0:
...     print('0 == True')
... else:
...     print('0 == False')
...
0 == False

The other issue

>>> word = "pizza"
>>> word[1:3]
'iz'
>>> word[-4:3]
'iz'

If the first index is larger than (or equal to) the second index, yields empty string:

>>> word[4:3]
''
>>> word[3:3]
''

Same for negative index:

>>> word[-1:3]
''

Upvotes: 3

Related Questions