Aug-23-2019, 08:07 AM
The purpose of the exercise is to take a string which says: "happy_birthday" and then use slicing to have the interpreter print just ‘happy’.
Take a look at these Python shell outputs:
My feeble answer to my own question is that programming in general involves symbol attribution like in algebra where words or symbols invoke an operation that substitute one symbol with another. So in my case the syntax of
Is this mostly correct? Or am I way off? How might one of you correct or add to my explanation here?
For my future reference, this Udemy instructor Ziyad Yehia refers to this code in "Quiz 3: Slices Quiz". This exercise is in between module #27 and 28 under Section #5. The course is titled "The Python Bible: Everything You Need to Program in Python". This is a course which is not for credit. It's just for fun.
Take a look at these Python shell outputs:
>>> string = "happy_birthday" >>> string[:] 'happy_birthday' >>> string 'happy_birthday' >>> string[:'birthday'] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: slice indices must be integers or None or have an __index__ method >>> string[ :string.index("_") ] 'happy' >>> string[0 : string.index("birthday") ] 'happy_'Line 6 is invalid because it’s not possible for slicing arguments to include strings. But line 10 takes a string as an argument to slice with and it is valid. Why are strings invalid (like at line 6) while other times parses as valid (like at line 10)?
My feeble answer to my own question is that programming in general involves symbol attribution like in algebra where words or symbols invoke an operation that substitute one symbol with another. So in my case the syntax of
string.index(“_”)
calls the index method on the string variable which refers to the placement of the underscore which in this case turns out to be position 5 of the given string "happy_birthday". So to complete the slice, "happy_birthday" is read as just "happy” because the slice starts at 0 and ends at the position 5. Is this mostly correct? Or am I way off? How might one of you correct or add to my explanation here?
For my future reference, this Udemy instructor Ziyad Yehia refers to this code in "Quiz 3: Slices Quiz". This exercise is in between module #27 and 28 under Section #5. The course is titled "The Python Bible: Everything You Need to Program in Python". This is a course which is not for credit. It's just for fun.