How to test characters of a string
Christian Gollwitzer
auriocus at gmx.de
Tue Jun 7 18:01:20 EDT 2022
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:
> 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.
^ is "starts with"
\d is any digit
\s is any space
+ is at least one
* is nothing or one of
Christian
More information about the Python-list
mailing list