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
  String slicing and loop iteration divyansh 9 2,182 Jun-07-2020, 10:29 PM
Last Post: divyansh
  String slicing divyansh 6 1,315 May-31-2020, 06:15 AM
Last Post: pyzyx3qwerty
  question: finding multiple strings within string djf123 4 1,151 May-16-2020, 01:00 PM
Last Post: snippsat
  Accepting inputs str vs int lbtdne 2 796 May-14-2020, 01:45 PM
Last Post: lbtdne
  string slicing help oli_action 2 877 Mar-22-2020, 09:57 AM
Last Post: oli_action
  Problem with accepting multiple string inputs Ryan_Todd 5 1,237 Jan-22-2020, 06:12 PM
Last Post: buran
  MySQLdb._exceptions.ProgrammingError: not enough arguments for format string. farah97 0 1,802 Jan-22-2020, 03:49 AM
Last Post: farah97
  signal.itimer() not accepting keyword arguments Skaperen 2 956 Dec-19-2019, 12:14 AM
Last Post: Skaperen
  Split a long string into other strings with no delimiters/characters krewlaz 4 1,156 Nov-15-2019, 02:48 PM
Last Post: ichabod801
  Slicing and printing two halfs of an email address (Udemy) Drone4four 5 1,306 Aug-26-2019, 09:01 AM
Last Post: wavic

Forum Jump:

User Panel Messages

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