Python Forum
slicing question - 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: slicing question (/thread-31717.html)



slicing question - DPaul - Dec-29-2020

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


RE: slicing question - deanhystad - Dec-29-2020

def printslice(fname,x=1):
    print(fname[0:x])
 
printslice('Jeremy')
printslice('Jeremy',-1)
printslice('Jeremy', None)
Output:
J Jerem Jeremy



RE: slicing question - DPaul - Dec-29-2020

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)


RE: slicing question - deanhystad - Dec-29-2020

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?


RE: slicing question - DPaul - Dec-30-2020

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


RE: slicing question - DPaul - Dec-30-2020

Still, what about an even simpler solution:

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

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