Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way to obtain the numeric prefix of a string

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.

like image 254
barak manos Avatar asked Mar 08 '16 12:03

barak manos


People also ask

How do you find the prefix of a string?

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".


1 Answers

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' 
like image 151
Mazdak Avatar answered Sep 21 '22 02:09

Mazdak