Python - 提取字符串直到数字
给定一个字符串,提取其所有内容,直到第一次出现数字字符。
Input : test_str = “geeksforgeeks7 is best”
Output : geeksforgeeks
Explanation : All characters before 7 are extracted.
Input : test_str = “2geeksforgeeks7 is best”
Output : “”
Explanation : No character extracted as 1st letter is numeric.
方法 #1:使用 isdigit() + index() + 循环
上述功能的组合可以用来解决这个问题。在此,我们使用 isdigit() 检查 numeric 的第一次出现, index() 用于获取所需的索引,直到需要提取哪些内容。
Python3
# Python3 code to demonstrate working of
# Extract String till Numeric
# Using isdigit() + index() + loop
# initializing string
test_str = "geeks4geeks is best"
# printing original string
print("The original string is : " + str(test_str))
# loop to iterating characters
temp = 0
for chr in test_str:
# checking if character is numeric,
# saving index
if chr.isdigit():
temp = test_str.index(chr)
# printing result
print("Extracted String : " + str(test_str[0 : temp]))
Python3
# Python3 code to demonstrate working of
# Extract String till Numeric
# Using regex()
import re
# initializing string
test_str = "geeks4geeks is best"
# printing original string
print("The original string is : " + str(test_str))
# regex to get all elements before numerics
res = re.findall('([a-zA-Z ]*)\d*.*', test_str)
# printing result
print("Extracted String : " + str(res[0]))
输出
The original string is : geeks4geeks is best
Extracted String : geeks
方法 #2:使用 regex()
这是可以执行此任务的另一种方式。使用适当的 regex(),可以在可能的数字之前获取内容。
Python3
# Python3 code to demonstrate working of
# Extract String till Numeric
# Using regex()
import re
# initializing string
test_str = "geeks4geeks is best"
# printing original string
print("The original string is : " + str(test_str))
# regex to get all elements before numerics
res = re.findall('([a-zA-Z ]*)\d*.*', test_str)
# printing result
print("Extracted String : " + str(res[0]))
输出
The original string is : geeks4geeks is best
Extracted String : geeks