How do I remove all characters after a certain one, inside a list

Viewed 65

my problem is:

I have a list which, after numerous cleanup, features elements which looks like '455XYZ455'. I'm trying to remove everything after X, but it is inside a list. The code that allows me to do this is the following:

check = [re.sub(r'\W', '', i) for i in content]
# print(check)
check2 = [re.sub('[aclassnewpagehref]', '', i) for i in check]
# print(check2)
check3 = [re.sub('[/<=""]', '', i) for i in check2]
# print(check3)
check4 = [item for item in check3 if item != '']
print(check4)

As expected it gives me just like above, a lot of '455XYZ455'. I just want the '455', but this is a list. Being a complete beginner in Python, I am entirely stuck. Thank you for reading and perhaps helping me!

2 Answers

You can capture the first digits in group 1 that you want to keep and remove the rest starting from X.

\A(\d+)X.*\Z

Explanation

  • \A Start of string
  • (\d+)X Capture 1+ digits in group 1, then match X
  • .*\Z Match any char 0+ times and assert the end of the string

regex demo

For example

import re
final = ["455XYZ455", "455XYZ455"]
for item in final:
    print(re.sub(r"^(\d+)X.*\Z", r"\1", item))

Output

455
455

You can do this just by using split without regex.Suppose the string '455XYZ455' is in variable a.

s = a.split('x')[0]

Here a will be split by 'x' and it will return the list of parts before and after 'x' but as you need just the part before 'x' , I've assigned the first element of list to s.

Related