How to test characters of a string

De ongekruisigde ongekruisigde at news.eternal-september.org
Tue Jun 7 18:18:17 EDT 2022


On 2022-06-08, Christian Gollwitzer <auriocus at gmx.de> wrote:
> Am 07.06.22 um 21:56 schrieb Dave:
>> It depends on the language I’m using, in Objective C, I’d use isNumeric, just wanted to know what the equivalent is in Python.
>> 
>
> Your problem is also a typical case for regular expressions. You can 
> create an expression for "starts with any number of digits plus optional 
> whitespace" and then replace this with nothing:

Regular expressions are overkill for this and much slower than the
simple isdigit based solution.


>> chris at linux-tb9f:~> ipython
>> Python 3.6.15 (default, Sep 23 2021, 15:41:43) [GCC]
>> Type 'copyright', 'credits' or 'license' for more information
>> IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.
>> 
>> In [1]: import re                                                                                                                                                                        
>> 
>> In [2]: s='05 Trinket'                                                                                                                                                                   
>> 
>> In [3]: re.sub(r'^\d+\s*', '', s)                                                                                                                                                        
>> Out[3]: 'Trinket'
>> 
>
> If it doesn't match, it will do nothing:
>
>> In [4]: s='Es geht los'                                                                                                                                                                  
>> 
>> In [5]: re.sub(r'^\d+\s*', '', s)                                                                                                                                                        
>> Out[5]: 'Es geht los'
>
> Some people on this list don't like regexes but for tasks like this they 
> are made and working well.

Regular expressions are indeeed extremely powerful and useful but I tend
to avoid them when there's a (faster) normal solution.


> ^ is "starts with"
> \d is any digit
> \s is any space
> + is at least one
> * is nothing or one of
>
> Christian

-- 
<StevenK> You're rewriting parts of Quake in *Python*?
<knghtbrd> MUAHAHAHA


More information about the Python-list mailing list