从字符串提取数字后缀的Python程序
鉴于字符内嵌有数字的字符串。任务是编写一个Python程序来提取所有尾随的数字,即在字符串的后缀处。
例子:
Input : test_str = “GFG04”
Output : 04
Explanation : 04 is suffix of string and number hence extracted.
Input : test_str = “GFG143”
Output : 143
Explanation : 143 is suffix of string and number hence extracted.
方法 #1:使用循环 + isdigit() +切片
在这里,使用切片反转字符串,并使用 isdigit 记录第一个非数字元素的出现,最后将列表切片直到元素并再次反转以获得后缀编号。
Python3
# Python3 code to demonstrate working of
# Extract Suffix numbers
# Using loop + isdigit() + slicing
# initializing string
test_str = "GFG04"
# printing original string
print("The original string is : " + str(test_str))
# loop for fetching the 1st non digit index
rev_str = test_str[::-1]
temp_idx = 0
for idx, ele in enumerate(rev_str):
if not ele.isdigit():
temp_idx = idx
break
# reversing the extracted string to
# get number
res = rev_str[:temp_idx][::-1]
# printing result
print("Suffix number : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Suffix numbers
# Using regex
import re
# initializing string
test_str = "GFG04"
# printing original string
print("The original string is : " + str(test_str))
# regex to extract number
res = re.search(r"(\d+)$", test_str).group()
# printing result
print("Suffix number : " + str(res))
输出
The original string is : GFG04
Suffix number : 04
方法#2:使用正则表达式
可以使用适当的正则表达式来解决这个问题。为问题提供了紧凑的解决方案。
蟒蛇3
# Python3 code to demonstrate working of
# Extract Suffix numbers
# Using regex
import re
# initializing string
test_str = "GFG04"
# printing original string
print("The original string is : " + str(test_str))
# regex to extract number
res = re.search(r"(\d+)$", test_str).group()
# printing result
print("Suffix number : " + str(res))
输出
The original string is : GFG04
Suffix number : 04