'Printing string range in Python

s ="XII"

roman = {"I":1, "IV":4, "V":5, "IX":9, "X":10, "XL":40, "L":50, 
                "XC":90, "C":100, "CD":400, "D":500, "CM":900, "M":1000}
out = 0
n = len(s)
i = 0

while i < n:
    
    print (s[i:i+1])
    
    i = i + 1

The output of the above code is

X
I
I
s ="XII"

roman = {"I":1, "IV":4, "V":5, "IX":9, "X":10, "XL":40, "L":50, 
                "XC":90, "C":100, "CD":400, "D":500, "CM":900, "M":1000}
out = 0
n = len(s)
i = 0

while i < n:
    
    print (s[i:i+2])
    
    i = i + 1

And, the output of the above code

XI
II
I

I have changed print (s[i:i+1]) to print (s[i:i+2])

Why it does not increment when I am using (s[i:i+1]) ? I just wanted to understand the behavior in detail.

Does it assign the same value if we use +1 ?



Solution 1:[1]

The slicing of s is non-inclusive.

s[start:end]

Meaning the output is up to but not including the end value. This means that the line

print (s[i:i+1])

is equivalent to

print (s[i])

According to this reference (https://blog.finxter.com/daily-python-puzzle-overshoot-index-slicing/)

A little-known feature of slicing is that it has robust end indices. Slicing is robust even if the end index is greater than the maximal sequence index. The slice just takes all elements up to the maximal element. If the start index is out of bounds as well, it returns the empty slice.

The follow code gives

s ="123"

roman = {"I":1, "IV":4, "V":5, "IX":9, "X":10, "XL":40, "L":50, 
                "XC":90, "C":100, "CD":400, "D":500, "CM":900, "M":1000}
out = 0
n = len(s)
i = 0

while i < n:
    
    print (s[i:i+2])
    
    
    i = i + 1

print(s[5:7])

gives:

12
23
3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Klimunmm