Python Forum
Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) (/thread-20643.html)



Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) - Drone4four - Aug-23-2019

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:

>>> 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.


RE: Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) - ThomasL - Aug-23-2019

string.index("_") evaluates to the index position of the underline "_" which is 5.
So string[:string.index("_")] is equivalent to string[:5] which gives you "happy"

found this one here https://www.geeksforgeeks.org/python-string-index-applications/


RE: Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) - perfringo - Aug-23-2019

My feeble mind raises ValueError when I see courses/books with titles consisting "Everything you need...", "... in 7 days" etc. In this particular case it also tries to raise TypeError because it's suspicious that this is not question but course promotion. But this is me and games my mind plays.

Regarding question. Why do you think that in both cases there are strings? There is very little effort to find types in Python:

>>> s = "happy_birthday"
>>> type('birthday')
<class 'str'>
>>> type(s.index('birthday'))
<class 'int'>
>>> s.index('birthday')
6
There is built-in help in Python and it's always good to start from there:

>>> help(str.index)
Help on method_descriptor:

index(...)
    S.index(sub[, start[, end]]) -> int
    
    Return the lowest index in S where substring sub is found, 
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Raises ValueError when the substring is not found.
(END)



RE: Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) - newbieAuggie2019 - Aug-23-2019

Hi!

Quote: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’.

I prefer to keep things simple, if possible, so based on your own answer in another post:

https://python-forum.io/Thread-Slicing-and-printing-two-halfs-of-an-email-address-Udemy

I made a small program:

print("\nIf you are sure that your string is let's say, greetings = 'happy_birthday' and you want to slice it and print just the first part ('happy') then:")
greetings = 'happy_birthday'
print("\nYour string is greetings = 'happy_birthday'.")
first_part = greetings.split('_')[0]
print(f'\nHere is your first_part: {first_part}')
and here is the output:

Output:
If you are sure that your string is let's say, greetings = 'happy_birthday' and you want to slice it and print just the first part ('happy') then: Your string is greetings = 'happy_birthday'. Here is your first_part: happy
All the best,


RE: Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) - Drone4four - Aug-23-2019

@ThomasL: You did a splendid job clarifying the syntax and semantics as you explain the index method.

@perfringo: I appreciate your sense of humour regarding the ValueError pun. Your use of type() and help() is instructive.

@newbieAuggie2019: That is certainly a creative way of replicating the same operation using the split() method instead of the index() method.

I set up a second string which is similar to the first but which this time is separated by a period “.” See here:

>>> string_two = "happy.birthday"
>>> string_two[string_two.index("."):]
'.birthday'
I shifted the casting method to the opposite side of the colon so that it grabs ‘birthday’ (instead of ‘happy’). However as you can see, the period is included. To omit the period, I just added “+1”. See here:

>>> string_two[string_two.index(".")+1:]
'birthday'
>>> 
Hooray!

I feel like I have come to know slicing much better now. I appreciate the help from all of you. Thanks.