[Python-ideas] Split, slice, join and return "syntax" for str
Steven D'Aprano
steve at pearwood.info
Sun Mar 4 19:12:50 EST 2018
On Sun, Mar 04, 2018 at 12:11:16PM -0800, Michel Desmoulin wrote:
> But, first, they are not common enough so that it's hard to do:
>
> spam = docs.python.org"
> eggs = 'wiki.' + '.'.join(spams.split('.')[1:])
In a more realistic case, the delimiter is not necessarily a constant,
nor will you always want to replace the first item.
So you would be writing:
delimiter.join(
spam.split(delimiter)[:n-1] +
['wiki'] + spam.split(delimiter)[n+1:]
)
Suddenly it's a lot less attractive to be typing out each time.
It is a good candidate for a helper function:
def replace_field(string, delimiter, position, new, start=0, end=None):
fields = string[start:end].split(delimiter)
fields[position] = new
string = (string[:start] + delimiter.join(fields)
+ ('' if end is None else string[end:]))
return string
That's not the most efficient implementation, and it isn't thoroughly
tested/debugged, but it ought to be good enough for casual use.
Personally, if this were available as a string method I think I'd use
this quite frequently, certainly more often than I use some other string
methods like str.partition.
> It's not that long to type, and certainly is not happening in every
> single script you do.
Speak for yourself :-)
No, not literally every script. (If that were the requirement to be a
string method, strings would have no methods.) But I think it is common
enough that I'd be happy for it to be a string method.
--
Steve
More information about the Python-ideas
mailing list