Python Forum
Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy)
#1
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.
Reply
#2
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-str...lications/
Reply
#3
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)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
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-a...ress-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,
newbieAuggie2019

"That's been one of my mantras - focus and simplicity. Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it's worth it in the end because once you get there, you can move mountains."
Steve Jobs
Reply
#5
@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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python3 string slicing Luchano55 4 534 Feb-17-2024, 09:40 AM
Last Post: Pedroski55
  Trying to understand strings and lists of strings Konstantin23 2 699 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  Am I wrong or is Udemy wrong? String Slicing! Mavoz 3 2,387 Nov-05-2022, 11:33 AM
Last Post: Mavoz
  Passing string functions as arguments Clunk_Head 3 1,209 Jun-15-2022, 06:00 AM
Last Post: Gribouillis
  Splitting strings in list of strings jesse68 3 1,703 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Search multiple CSV files for a string or strings cubangt 7 7,842 Feb-23-2022, 12:53 AM
Last Post: Pedroski55
  TypeError: not enough arguments for format string MaartenRo 6 2,860 Jan-09-2022, 06:46 PM
Last Post: ibreeden
  String slicing and loop iteration divyansh 9 4,619 Jun-07-2020, 10:29 PM
Last Post: divyansh
  String slicing divyansh 6 3,283 May-31-2020, 06:15 AM
Last Post: pyzyx3qwerty
  question: finding multiple strings within string djf123 4 2,901 May-16-2020, 01:00 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020