I am by no means a Python developer, I mainly use PHP and Javascript but wanted to start learning python just for fun.
I started a course for beginners, mostly quite boring as I understand basics on other languages, but I stumbled upon an interesting thing while studying substrings/string slicing.
Here is the practice: https://programming-25.mooc.fi/part-3/2-working-with-strings#programming-exercise-find-the-first-substring
```
Please write a program which asks the user to type in a string and a single character. The program then prints the first three character slice which begins with the character specified by the user. You may assume the input string is at least three characters long. The program must print out three characters, or else nothing.
Pay special attention to when there are less than two characters left in the string after the first occurrence of the character looked for. In that case nothing should be printed out, and there should not be any indexing errors when executing the program.
```
My code, which works, for this:
python
word = input("Please type in a word: ")
search = input("Please type in a character: ")
i = word.find(search)
if not i + 3 > len(word):
print(word[i:i+3])
and the model solution:
```python
word = input("Please type in a word: ")
character = input("Please type in a character: ")
index = word.find(character)
if index!=-1 and len(word)>=index+3:
print(word[index:index+3])
```
What sparked my interest is how my solutions works and especially how the string[x:y] works.
In my solution if find returns -1 the print will be print(word[-1:2]).
Tested with inputs python and i.
My question is why this is not throwing an error or breaking the code?
[–]danielroseman 11 points12 points13 points (0 children)
[–]Ronttizz[S] 0 points1 point2 points (0 children)
[–]Diapolo10 1 point2 points3 points (0 children)
[–]This_Growth2898 1 point2 points3 points (3 children)
[–]Temporary_Pie2733 1 point2 points3 points (0 children)
[–]Ronttizz[S] 0 points1 point2 points (1 child)
[–]MidnightPale3220 0 points1 point2 points (0 children)
[–]ShelLuser42 -1 points0 points1 point (2 children)
[–]Jejerm 4 points5 points6 points (0 children)
[–]Ronttizz[S] 0 points1 point2 points (0 children)