What is the cleanest way to obtain the numeric prefix of a string in Python?
By "clean" I mean simple, short, readable. I couldn't care less about performance, and I suppose that it is hardly measurable in Python anyway.
For example:
Given the string '123abc456def'
, what is the cleanest way to obtain the string '123'
?
The code below obtains '123456'
:
input = '123abc456def' output = ''.join(c for c in input if c in '0123456789')
So I am basically looking for some way to replace the if
with a while
.
A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string. Example 1: Input: words = ["a","b","c","ab","bc","abc"], s = "abc" Output: 3 Explanation: The strings in words which are a prefix of s = "abc" are: "a", "ab", and "abc".
You can use itertools.takewhile
which will iterate over your string (the iterable argument) until it encounters the first item which returns False
(by passing to predictor function):
>>> from itertools import takewhile >>> input = '123abc456def' >>> ''.join(takewhile(str.isdigit, input)) '123'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With