Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
slicing question
#1
Hi,

I have a slicing question that boils down to this:
def printslice(fname,x):
    print(fname[x])

printslice('Jeremy',0)
The number (2nd argument) indicates how many letters I want from the name.
Ususally this is going to be 1 : the initial, in this case "J", position 0.
But what (number) should I pass when I want the whole name, so no slicing?

If that is not possible, of course an if 0: do this, else: do the whole name, is a workaround.
I can also calculate the length of the string and do an [x:y] slice.

But maybe there is a simpler solution?

thanks,
Paul
Reply
#2
def printslice(fname,x=1):
    print(fname[0:x])
 
printslice('Jeremy')
printslice('Jeremy',-1)
printslice('Jeremy', None)
Output:
J Jerem Jeremy
Reply
#3
I like it !

thx,
Paul

PS: You may have noticed that i made a typo in the question.
It was not "how many letters I want", but "which letter position i want" (which is relevant to the problem i have)
Reply
#4
The subject mentions slicing, the example code does indexing, and the post text talks about slicing again. I was confused and just answered the slicing question. Now I am more confused.

What are you trying to do?
Reply
#5
You are right, i did mix the words up.
I started out with indexing, but i felt i was using too many code lines,
to get either one or all letters. (And using the second argument more or less as a True/False flag)

By introducing the "None" argument, which i did not know was possible, we settled for slicing

But, i did get some new ideas out of the exercise.
Thanks,
Paul
Reply
#6
Still, what about an even simpler solution:

def printslice(fname,x):
    print(fname[0:x])

printslice('Jeremy',1)
printslice('Jeremy',100)
Paul
Reply


Forum Jump:

User Panel Messages

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