[Python-ideas] Split, slice, join and return "syntax" for str
Michel Desmoulin
desmoulinmichel at gmail.com
Sun Mar 4 15:11:16 EST 2018
Even if replace would be a better fit, I can see why doing those 3
operations in one row can be valuable.
But, first, they are not common enough so that it's hard to do:
spam = docs.python.org"
eggs = 'wiki.' + '.'.join(spams.split('.')[1:])
It's not that long to type, and certainly is not happening in every
single script you do.
But let's say for the sake of argument you do a lot of cmd parsing, with
a lot of split and join. Just make a helper:
def rearrange(string, sep=None, start=None, stop=None, step=None):
return sep.join(string.split(sep)[start:stop:step])
And then you can do:
spam = docs.python.org"
eggs = 'wiki.' + rearrange(spam, '.', 1)
Simple, easy, no need to change Python.
Le 04/03/2018 à 09:59, Andrés Delfino a écrit :
> Hi!
>
> I was thinking: perhaps it would be nice to be able to quicky split a
> string, do some slicing, and then obtaining the joined string back.
>
> Say we have the string: "docs.python.org <http://docs.python.org>", and
> we want to change "docs" to "wiki". Of course, there are a ton of
> simpler ways to solve this particular need, but perhaps str could have
> something like this:
>
> spam = "docs.python.org <http://docs.python.org>"
> eggs = "wiki." + spam['.'][1:]
> print(eggs) #wiki.python.org <http://wiki.python.org>
>
> A quick implementation to get the idea and try it:
>
> class Mystr(str):
> def __getitem__(self, item):
> if isinstance(item, str):
> return Mystr_helper(self, item)
> else:
> return super().__getitem__(item)
>
> class Mystr_helper:
> def __init__(self, obj, sep):
> self.obj = obj
> self.sep = sep
> def __getitem__(self, item):
> return self.sep.join(self.obj.split(self.sep)[item])
>
> What are your thoughts?
>
> Greetings from Argentina.
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
More information about the Python-ideas
mailing list