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

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

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

给定一个字符串。任务是在字符串中打印数字前缀(如果它存在于字符串中)。下面给出了一些解决任务的方法。

方法#1:使用朴素方法

# Python code to demonstrate
# to get numeric prefix in string
# if present
  
# initialising string
ini_string = "123abcjw"
ini_string2 = "abceddfgh"
  
# printing string and its length
print ("initial string : ", ini_string, ini_string2)
  
# code to find numeric prefix in string
res1 = ''.join(c for c in ini_string if c in '0123456789')
res2 = ''.join(c for c in ini_string2 if c in '0123456789')
  
  
# printing resultant string
print ("first string result: ", str(res1))
print ("second string result: ", str(res2))
输出:
initial string :  123abcjw abceddfgh
first string result:  123
second string result:

方法#2:使用takewhile

# Python code to demonstrate
# to get numeric prefix in string
# if present
from itertools import takewhile
  
# initialising string
ini_string = "123abcjw"
ini_string2 = "abceddfgh"
  
# printing string and its length
print ("initial string : ", ini_string, ini_string2)
  
# code to find numeric prefix in string
res1 = ''.join(takewhile(str.isdigit, ini_string))
res2 = ''.join(takewhile(str.isdigit, ini_string2))
  
# printing resultant string
print ("first string result: ", res1)
print ("second string result: ", res2)
输出:
initial string :  123abcjw abceddfgh
first string result:  123
second string result:


方法#3:使用re.sub

# Python code to demonstrate
# to get numeric prefix in string
# if present
import re
  
# initialising string
ini_string = "123abcjw"
ini_string2 = "abceddfgh"
  
# printing string and its length
print ("initial string : ", ini_string, ini_string2)
  
# code to find numeric prefix in string
res1 = re.sub('\D.*', '', ini_string)
res2 = re.sub('\D.*', '', ini_string2)
  
  
# printing resultant string
print ("first string result: ", str(res1))
print ("second string result: ", str(res2))
输出:
initial string :  123abcjw abceddfgh
first string result:  123
second string result:

使用方法#4:使用re.findall

# Python code to demonstrate
# to get numeric prefix in string
# if present
import re
  
# initialising string
ini_string = "123abcjw"
ini_string2 = "abceddfgh"
  
# printing string and its length
print ("initial string : ", ini_string, ini_string2)
  
# code to find numeric prefix in string
res1 = ''.join(re.findall('\d+', ini_string))
res2 = ''.join(re.findall('\d+', ini_string2))
  
# printing resultant string
print ("first string result: ", str(res1))
print ("second string result: ", str(res2))
输出:
initial string :  123abcjw abceddfgh
first string result:  123
second string result: