Cutting slices
MRAB
python at mrabarnett.plus.com
Sun Mar 5 20:56:35 EST 2023
On 2023-03-06 00:28, dn via Python-list wrote:
> On 06/03/2023 11.59, aapost wrote:
>> On 3/5/23 17:43, Stefan Ram wrote:
>>> The following behaviour of Python strikes me as being a bit
>>> "irregular". A user tries to chop of sections from a string,
>>> but does not use "split" because the separator might become
>>> more complicated so that a regular expression will be required
>>> to find it. But for now, let's use a simple "find":
>>> |>>> s = 'alpha.beta.gamma'
>>> |>>> s[ 0: s.find( '.', 0 )]
>>> |'alpha'
>>> |>>> s[ 6: s.find( '.', 6 )]
>>> |'beta'
>>> |>>> s[ 11: s.find( '.', 11 )]
>>> |'gamm'
>>> |>>>
>>>
>>> . The user always inserted the position of the previous find plus
>>> one to start the next "find", so he uses "0", "6", and "11".
>>> But the "a" is missing from the final "gamma"!
>>> And it seems that there is no numerical value at all that
>>> one can use for "n" in "string[ 0: n ]" to get the whole
>>> string, isn't it?
>>>
>>>
>>
>> I would agree with 1st part of the comment.
>>
>> Just noting that string[11:], string[11:None], as well as string[11:16]
>> work ... as well as string[11:324242]... lol..
>
> To expand on the above, answering the OP's second question: the numeric
> value is len( s ).
>
> If the repetitive process is required, try a loop like:
>
> >>> start_index = 11 #to cure the issue-raised
>
> >>> try:
> ... s[ start_index:s.index( '.', start_index ) ]
> ... except ValueError:
> ... s[ start_index:len( s ) ]
> ...
> 'gamma'
>
Somewhat off-topic, but...
When there was a discussion about a None-coalescing operator, I thought
that it would've been nice if .find and .rfind returned None instead of -1.
There have been times when I've wanted to find the next space (or
whatever) and have it return the length of the string if absent. That
could've been accomplished with:
s.find(' ', pos) ?? len(s)
Other times I've wanted it to return -1. That could've been accomplished
with:
s.find(' ', pos) ?? -1
(There's a place in the re module where .rfind returning -1 is just the
right value.)
In this instance, slicing with None as the end is just what's wanted.
Ah, well...
More information about the Python-list
mailing list