📜  Python|拆分字符串中的文本和数字

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

Python|拆分字符串中的文本和数字

有时,我们有一个字符串,它由文本和数字组成(反之亦然),两者之间没有任何具体区别。可能有一个要求,我们需要将文本与数字分开。让我们讨论可以执行此操作的某些方式。

方法#1:使用re.compile() + re.match() + re.groups()
上述所有正则表达式函数的组合可用于执行此特定任务。在此我们编译一个正则表达式并将其匹配以将文本和数字分别分组到一个元组中。

# Python3 code to demonstrate working of
# Splitting text and number in string 
# Using re.compile() + re.match() + re.groups()
import re
  
# initializing string 
test_str = "Geeks4321"
  
# printing original string 
print("The original string is : " + str(test_str))
  
# Using re.compile() + re.match() + re.groups()
# Splitting text and number in string 
temp = re.compile("([a-zA-Z]+)([0-9]+)")
res = temp.match(test_str).groups()
  
# printing result 
print("The tuple after the split of string and number : " + str(res))
输出 :
The original string is : Geeks4321
The tuple after the split of string and number : ('Geeks', '4321')

方法 #2:使用re.findall()
正则表达式的轻微修改可以提供灵活性,以减少执行此特定任务所需的正则表达式函数的数量。 findall函数足以完成此任务。

# Python3 code to demonstrate working of
# Splitting text and number in string 
# Using re.findall()
import re
  
# initializing string 
test_str = "Geeks4321"
  
# printing original string 
print("The original string is : " + str(test_str))
  
# Using re.findall()
# Splitting text and number in string 
res = [re.findall(r'(\w+?)(\d+)', test_str)[0] ]
  
# printing result 
print("The tuple after the split of string and number : " + str(res))
输出 :
The original string is : Geeks4321
The tuple after the split of string and number : ('Geeks', '4321')