📜  Python|从给定的字符串中提取数字

📅  最后修改于: 2022-05-13 01:55:43.204000             🧑  作者: Mango

Python|从给定的字符串中提取数字

在编程时,有时我们只需要某种类型的数据而需要丢弃其他类型的数据。这类问题在数据科学领域很常见,由于数据科学在全球范围内使用Python ,因此了解如何提取特定元素非常重要。本文讨论了只能提取数字的某些方法。让我们讨论同样的问题。
方法 #1:使用 join() + isdigit() + filter()
可以使用上述功能的组合来执行此任务。 filter函数过滤isdigit函数检测到的数字,join函数执行join函数的重构任务。

Python3
# Python3 code to demonstrate
# Extract digit string
# using join() + isdigit() + filter()
 
# initializing string
test_string = 'g1eeks4geeks5'
 
# printing original strings 
print("The original string : " + test_string)
 
# using join() + isdigit() + filter()
# Extract digit string
res = ''.join(filter(lambda i: i.isdigit(), test_string))
     
# print result
print("The digits string is : " + str(res))


Python3
# Python3 code to demonstrate
# Extract digit string
# using re
import re
 
# initializing string
test_string = 'g1eeks4geeks5'
 
# printing original strings 
print("The original string : " + test_string)
 
# using re
# Extract digit string
res = re.sub("\D", "", test_string)
     
# print result
print("The digits string is : " + str(res))


Python3
# Python3 code to demonstrate
# Extract digit string
s="g1eeks4geeks5"
#using for loop
for i in s:
  # using isdigit() function
  if(i.isdigit()):
    print(i,end="")


输出 :
The original string : g1eeks4geeks5
The digits string is : 145


方法#2:使用 re
正则表达式也可用于执行此特定任务。我们可以定义数字类型要求,使用“\D”,并且只从字符串中提取数字。

Python3

# Python3 code to demonstrate
# Extract digit string
# using re
import re
 
# initializing string
test_string = 'g1eeks4geeks5'
 
# printing original strings 
print("The original string : " + test_string)
 
# using re
# Extract digit string
res = re.sub("\D", "", test_string)
     
# print result
print("The digits string is : " + str(res))
输出 :
The original string : g1eeks4geeks5
The digits string is : 145

方法3:使用循环:

这个任务是通过使用 for 循环来完成的。

Python3

# Python3 code to demonstrate
# Extract digit string
s="g1eeks4geeks5"
#using for loop
for i in s:
  # using isdigit() function
  if(i.isdigit()):
    print(i,end="")
Output:
The original string : g1eeks4geeks5
The digits string is : 145