I'd like keep the first few characters of a string using a[:-3] etc. But I'd like to keep this -3 as a variable, so it could be a[:-1] so I will use a variable to dynamically slice the string using a[:-b], However, to use this format, how to keep all the characters like using a[:]? I don't want to use a[:len(a)] because I am passing this variable into a function where slcing is done. so I don't know string a outside the function. Thanks
def slicing_string(slice_variable):
a='mytext'
return a[:slice_variable]
b=slicing_string(-3)
b
How to keep all the character using this function without knowning string a
CodePudding user response:
You can pass in None
to make the slice go all the way to the end of the string as if there were nothing specified at all in that part of the slice expression:
>>> "mytext"[:None]
'mytext'
This works for all parts of the slice, of course:
>>> "mytext"[None:None:None]
'mytext'
>>> "mytext"[None:None:-1]
'txetym'
When you use the slice syntax with the subscript operator, what's happening under the covers is the construction of a slice
object with the :
separated expressions as parameters, and the slice object is what gets passed to the __getitem__
method; the constructor's default parameters are None
so you can pass None
explicitly as part of a slice and it's exactly as if you'd passed nothing.
>>> "mytext".__getitem__(slice(None, None, -1))
'txetym'
>>> "mytext"[slice(None, None, -1)]
'txetym'
>>> "mytext"[::-1]
'txetym'
CodePudding user response:
Try this:
def slicing_string(slice_variable):
a='mytext'
return a[:slice_variable] if slice_variable else a[:]
b=slicing_string(-3)
print(b)
b=slicing_string(None)
print(b)
To keep it simple:
When slice_variable
is None
, a[:slice_variable]
becomes a[:]
, which is equivalent to a[0:len(a)]
and returns all characters of the string a
.