[Python-ideas] More user-friendly version for string.translate()

Mikhail V mikhailwas at gmail.com
Mon Oct 24 16:30:22 EDT 2016


On 24 October 2016 at 20:02, Chris Barker <chris.barker at noaa.gov> wrote:
> On Mon, Oct 24, 2016 at 10:50 AM, Ryan Birmingham <rainventions at gmail.com>
> wrote:
>>
>> I also believe that using a text file would not be the best solution;
>> using a dictionary,
>
>
> actually, now that you mention it -- .translate() already takes a dict, so
> if youw ant to put your translation table in a text file, you can use a dict
> literal to do it:
>
> # contents of file:
>
>
> {
> 32: 95,
>
> 105: 64,
> 115: 36,
> }
>
> then use it:
>
> s.translate(ast.literal_eval(open("trans_table.txt").read()))
>
> now all you need is a tiny little utility function:
>
> def translate_from_file(s, filename):
>     return s.translate(ast.literal_eval(open(filename).read()))
>
>
> :-)
>
> -Chris
>

Yes making special file format is not a good option I agree.
Also of course it does not have sence to read it everytime if translate
is called in a loop with the same table. So it was merely a sketch of
behaviour.

But how would you with current translate function drop all characters
that are not in the table? so I can pass [deletechars] to the function but
this seems not very convenient to me -- very often I want to
drop them *all*, excluding some particular values.  This for example
is needed for filtering out all non-standard characters from paths, etc.
So in other words, there should be an option to control this behavior.
Probably I am missing something here, but I didn't find such solution
for translate() and that is main point of proposal actually.
It is all the same as translate() but with this extension it can cover
much more usage cases.


Mikhail


More information about the Python-ideas mailing list