📜  Python – 字符串中的前 K 个连续数字

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

Python – 字符串中的前 K 个连续数字

给定一个字符串和数字 K,提取前 K 个连续的数字来生成数字。

方法#1:使用循环

这是可以执行此任务的粗暴方式。在此,我们在列表中运行一个循环并检查当前数字是否存在有效的 N 个连续元素,如果是,我们返回这 N 个元素。

Python3
# Python3 code to demonstrate working of 
# First K consecutive digits in String
# Using loop
  
# initializing string
test_str = "geeks5geeks43isbest"
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K 
K = 2
  
# using loop to run through characters 
res = ""
for idx in range(len(test_str) - K + 1):
        is_num = True
          
        # check for valid number of consecutives
        for j in range(K):
            is_num = is_num & test_str[idx + j].isdigit()
              
        # extracting numbers 
        if is_num :
            res = ""
            for j in range(K):
                res += test_str[idx + j]
  
# printing result 
print("Required character digits : " + str(res))


Python3
# Python3 code to demonstrate working of 
# First K consecutive digits in String
# Using regex()
import re
  
# initializing string
test_str = "geeks5geeks43isbest"
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K 
K = 2
  
# using regex() to solve problem
temp = re.search('\d{% s}'% K, test_str)
res = (temp.group(0) if temp else '')
  
# printing result 
print("Required character digits : " + str(res))


输出
The original string is : geeks5geeks43isbest
Required character digits : 43

方法 #2:使用 regex()

这是可以执行此任务的另一种方式。在此,我们应用有效的正则表达式,处理后,结果作为出现返回,第一个返回。

Python3

# Python3 code to demonstrate working of 
# First K consecutive digits in String
# Using regex()
import re
  
# initializing string
test_str = "geeks5geeks43isbest"
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K 
K = 2
  
# using regex() to solve problem
temp = re.search('\d{% s}'% K, test_str)
res = (temp.group(0) if temp else '')
  
# printing result 
print("Required character digits : " + str(res)) 
输出
The original string is : geeks5geeks43isbest
Required character digits : 43