Python-仅输出字符串的整数

时间:2019-03-10 23:41:08

标签: python python-3.x python-3.6

因此,举个例子,假设程序中只有一行代码,而该行代码是n = input(),并且假设用户输入了random123。如何打印n时只打印n或123的整数?请注意,即使用户输入为random123random456,我也希望这样做。如果用户输入的是“ random123random456”,我希望它打印123456

3 个答案:

答案 0 :(得分:3)

您可以将生成器表达式与对str.isdigit方法的调用一起用作过滤器:

''.join(c for c in n if c.isdigit())

答案 1 :(得分:1)

另一种快速的方法是使用regular expressions

从字符串中删除所有非数字字符

示例:

bool isEqual(string str1, string str2)
{
   if ( str1.length() != str2.length() )
   {
      return false;
   }

   auto iter1 = begin(str1);
   auto end1 = end(str1);

   auto iter2 = begin(str2);
   auto end2 = end(str2);

   for ( ; iter1 != end1 && iter2 != end2; ++iter1, ++iter2 )
   {
      // This will also work.
      // if ( std::tolower(*iter1) != std::tolower(*iter2) )

      if ( std::toupper(*iter1) != std::toupper(*iter2) )
      {
         return false;
      }
   }

   // We come here only if we have compared all the characters
   // of BOTH the strings. In that case the strings are equal.

   return true;
}

此处\ D表示不同于0 ... 9的任何字符 然后可以将其替换为空字符

一些结果:

import re
test = "123string456"

result = re.sub('\D', '', test)

最诚挚的问候

答案 2 :(得分:0)

test = "123string456"
output = str()
for each in test:
    try:
        n = int(each)
        output = "{}{}".format(output,n)
    except:
        pass

print(output)