I'm new to python and am having difficulties to remove words in a string
9 - Saturday, 19 May 2012
above is my string I would like to remove all string to
19 May 2012
so I could easily convert it to sql date
here is the could that I tried
new_s = re.sub(',', '', '9 - Saturday, 19 May 2012')
But it only remove the "," in the String. Any help?
您可以使用string.split(',')
,您将获得
['9 - Saturday', '19 May 2012']
You are missing the .*
(matching any number of chars) before the ,
(and a space after it which you probably also want to remove:
>>> new_s = re.sub('.*, ', '', '9 - Saturday, 19 May 2012')
>>> new_s
'19 May 2012'
Your regex is matching a single comma only hence that is the only thing it removes.
You may use a negated character class ie [^,]*
to match everything until you match a comma and then match comma and trailing whitespace to remove it like this:
>>> print re.sub('[^,]*, *', '', '9 - Saturday, 19 May 2012')
19 May 2012
Regex is great, but for this you could also use .split()
test_string = "9 - Saturday, 19 May 2012"
splt_string = test_string.split(",")
out_String = splt_string[1]
print(out_String)
Outputs:
19 May 2012
If the leading ' '
is a propblem, you can remedy this with out_String.lstrip()
try this
a = "9 - Saturday, 19 May 2012"
f = a.find("19 May 2012")
b = a[f:]
print(b)
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.