This code is designed to remove everything but leave numbers
a = "1.1.1.1"
b = re.sub('[^0-9]', '', a)
but i want to preserve dots as well.
Try out
a = 1.1.1.1
b = re.sub('[^\d\.]', '', a)
instead. 0-9
can be replaced with \\d
because that matches all numerical characters, and the \\.
is necessary because the .
character is a wildcard.
Not using regular expression:
>>> ''.join(c for c in a if c.isdigit() or c == '.')
'1.1.1.1'
>>> a = 'hello.1.number'
>>> ''.join(c for c in a if c.isdigit() or c == '.')
'.1.'
>>> a='1.1.1.1'
>>> b = re.sub('[^0-9\.]', '', a)
>>> b
'1.1.1.1'
>>> a='comp.languages.python'
>>> b = re.sub('[^0-9.]', '', a)
>>> b
'..'
The []
means match only these characters.
The [^]
means match all characters EXCEPT these characters.
0-9
is 0123456789
.
is . but be careful with . because outside []
it is often used to match any single character
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.