简体   繁体   English

如何搜索字符串并提取所有特定字符?

[英]How can I search through a string and extract all specific characters?

So say that I have a string which is something along the lines of "One2three4".假设我有一个类似于“One2three4”的字符串。 Is it possible for me to look through the string and take the integers and put them in their own string, so my final result will be "24".我是否可以查看字符串并获取整数并将它们放入自己的字符串中,所以我的最终结果将是“24”。 Thanks谢谢

Using str.join() and str.isdigit() :使用str.join()str.isdigit()

>>> s = "One2three4"
>>> ''.join(c for c in s if c.isdigit())
'24'

This method looks through the string once and checks if each character is a digit or not;此方法查看字符串一次并检查每个字符是否为数字; the characters that satisfy this are joined into a new string.满足这个条件的字符被连接成一个新的字符串。 In complexity terms, this is O(n), and as we need to check every character in the string, this is the best we can do.就复杂性而言,这是 O(n),并且由于我们需要检查字符串中的每个字符,这是我们能做的最好的事情。

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

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