Home > Software design >  Remove all characters from string after the first digit with the least amount of code
Remove all characters from string after the first digit with the least amount of code

Time:05-30

So far, to remove all characters from a string after the first digit, I came up with

import re
s1 = "thishasadigit4here"
m = re.search(r"\d", s1)
result = s1[:m.start()]
print(result)

thishasadigit

Is there a compact way of coding this task?

CodePudding user response:

As mentioned in the comments shorter code does not always imply better code (although it can be fun to go golfing).

That said (with re imported and mystring having your string), how about this:

result = re.split(r"\d", mystring, maxsplit=1)[0]

See https://pynative.com/python-regex-split/ for more information.

CodePudding user response:

If it is just a digit you are trying to find, you probably don't need a regex -

import string
s1 = "thishasadigit4here"
min_digit_index = min(s1.find(_) for _ in string.digits if s1.find(_) > -1)
s1[:min_digit_index]
# 'thishasadigit'

All of that can be reduced to a single line -

import string
s1[:min(s1.find(_) for _ in string.digits if s1.find(_) > -1)]
# 'thishasadigit'
  • Related