📌  相关文章
📜  Python|获取给定字符串的数字前缀

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

Python|获取给定字符串的数字前缀

有时,在使用字符串时,我们可能会遇到需要获取字符串的数字前缀的情况。这种应用程序可以出现在各种领域,例如 Web 应用程序开发。让我们讨论可以执行此任务的某些方式。

方法 #1:使用re.findall()
正则表达式可用于执行此特定任务。在此,我们使用 findall函数来获取所有出现的数字,然后返回初始出现。

# Python3 code to demonstrate working of
# Get numeric prefix of string 
# Using re.findall()
import re
  
# initializing string 
test_str = "1234Geeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# Using re.findall()
# Get numeric prefix of string 
res = re.findall('\d+', test_str)
  
# printing result 
print("The prefix number at string : " + str(res[0]))
输出 :
The original string is : 1234Geeks
The prefix number at string : 1234

方法 #2:使用itertools.takewhile()
takewhile 的内置函数可用于执行提取所有数字直到出现字符的特定任务。

# Python3 code to demonstrate working of
# Get numeric prefix of string 
# Using itertools.takewhile()
from itertools import takewhile
  
# initializing string 
test_str = "1234Geeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# Using itertools.takewhile()
# Get numeric prefix of string 
res = ''.join(takewhile(str.isdigit, test_str))
  
# printing result 
print("The prefix number at string : " + str(res))
输出 :
The original string is : 1234Geeks
The prefix number at string : 1234