简体   繁体   English

Python从字符串中打印前N个整数

[英]Python print first N integers from a string

Is it possible without regex in python to print the first n integers from a string containing both integers and characters? 在python中没有正则表达式的情况下,是否可以从包含整数和字符的字符串中打印出前n个整数?

For instance: 例如:

string1 = 'test120202test34234e23424'
string2 = 'ex120202test34234e23424'

foo(string1,6)  => 120202
foo(string2,6) => 120202

Anything's possible without a regex. 没有正则表达式,一切皆有可能。 Most things are preferable without a regex. 没有正则表达式,大多数事情都是可取的。

On easy way is. 简单的方法是。

>>> str = 'test120202test34234e23424'
>>> str2 = 'ex120202test34234e23424'
>>> ''.join(c for c in str if c.isdigit())[:6]
'120202'
>>> ''.join(c for c in str2 if c.isdigit())[:6]
'120202'

You might want to handle your corner cases some specific way -- it all depends on what you know your code should do. 您可能想以某种特定的方式处理极端情况-这完全取决于您知道代码应该做什么。

>>> str3 = "hello 4 world"
>>> ''.join(c for c in str3 if c.isdigit())[:6]
'4'

And don't name your strings str ! 并且不要命名您的字符串str

You can remove all the alphabets from you string with str.translate and the slice till the number of digits you want, like this 您可以使用str.translate和slice删除字符串中的所有字母,直到所需的位数为止,就像这样

import string

def foo(input_string, num):
    return input_string.translate(None, string.letters)[:num]

print foo('test120202test34234e23424', 6)   # 120202
print foo('ex120202test34234e23424',   6)   # 120202

Note: This simple technique works only in Python 2.x 注意:此简单技术仅在Python 2.x中有效

But the most efficient way is to go with the itertools.islice 但是最有效的方法是使用itertools.islice

from itertools import islice

def foo(input_string, num):
    return "".join(islice((char for char in input_string if char.isdigit()),num))

This is is the most efficient way because, it doesn't have to process the entire string before returning the result. 这是最有效的方法,因为在返回结果之前,不必处理整个字符串。

If you didn't want to process the whole string - not a problem with the length of strings you give as an example - you could try: 如果您不想处理整个字符串-作为示例给出的字符串长度不是问题-您可以尝试:

import itertools
"".join(itertools.islice((c for c in str2 if c.isdigit()),0,5))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM