Valek
Valek

Reputation: 125

Remove words until a specific character is reached

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?

Upvotes: 0

Views: 72

Answers (5)

ArMaNdO
ArMaNdO

Reputation: 46

try this

a = "9 - Saturday, 19 May 2012"
f = a.find("19 May 2012")
b = a[f:]
print(b)

Upvotes: 0

Mohamed ِRadwan
Mohamed ِRadwan

Reputation: 797

You can use string.split(',') and you will get

['9 - Saturday', '19 May 2012']

Upvotes: 2

NBlaine
NBlaine

Reputation: 493

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()

Upvotes: 0

anubhava
anubhava

Reputation: 785611

Your regex is matching a single comma only hence that is the only thing it removes.

You may use a negated character class i.e. [^,]* 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

Upvotes: 1

fferri
fferri

Reputation: 18950

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'

Upvotes: 1

Related Questions