获取字符串数字前缀的最简洁方法 [英] Cleanest way to obtain the numeric prefix of a string

查看:40
本文介绍了获取字符串数字前缀的最简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中获取字符串数字前缀的最简洁方法是什么?

干净"是指简单、简短、易读.我完全不关心性能,而且我想无论如何在 Python 中它几乎是无法衡量的.

例如:

给定字符串'123abc456def',获得字符串'123'的最简洁方法是什么?

下面的代码得到'123456':

input = '123abc456def'output = ''.join(c for c in input if c in '0123456789')

所以我基本上是在寻找某种方法来将 if 替换为 while.

解决方案

您可以使用 itertools.takewhile 它将遍历您的字符串(可迭代参数),直到遇到返回 False 的第一项(通过传递给预测函数):

<预><代码>>>>from itertools import takewhile>>>输入 = '123abc456def'>>>''.join(takewhile(str.isdigit, input))'123'

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.

解决方案

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'

这篇关于获取字符串数字前缀的最简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆