user297850
user297850

Reputation: 8015

remove the substring starting with some given characters

There are some strings with the following pattern '{substring1}.{substring2}'. I only want to keep the substring1. For instance, for e23.hd, I only want to keep e23.

Here is a code for testing

a = 'e23.hd'
import re
re.sub(".*","",a)
a

e23.hd

I tried to use .* to represent the .{substring2}, it seems it does not work.

Upvotes: 1

Views: 55

Answers (1)

Andreas
Andreas

Reputation: 9207

Are there any reason you use regex? This can be solved without regex. But if you really want to, here the regex way:

a = 'e23.hd'
import re
re.sub("\..*","",a)
print(a)
#'e23'

or without regex:

print(a.split(".")[0])
#'e23'

or without regex and if multiple "." are possible:

print(a.rsplit(".", 1)[0])
#'e23'

Upvotes: 3

Related Questions