在 Python 中将字符串拆分为文本和数字

在 Python 中将字符串拆分为文本和数字

Split a string into text and number in Python

使用该re.split()方法将字符串拆分为文本和数字,例如
my_list = re.split(r'(\d+)', my_str). re.split()方法将拆分数字上的字符串,并将它们仍包含在列表中。

主程序
import re my_str = 'hello123' my_list = re.split(r'(\d+)', my_str) # 👇️ ['hello', '123', ''] print(my_list)

请注意,我们在末尾得到一个空字符串,因为字符串中的最后一个字符是数字。

您可以使用该filter()方法从列表中删除任何空字符串。

主程序
import re my_str = 'hello123' my_list = list(filter(None, re.split(r'(\d+)', my_str))) # 👇️ ['hello', '123'] print(my_list)

filter函数接受一个函数和一个可迭代对象作为参数,并从可迭代对象的元素构造一个迭代器,函数返回一个真值。

If you pass None for the function argument, all falsy elements of the iterable
are removed.

The re.split method takes
a pattern and a string and splits the string on each occurrence of the pattern.

The parentheses in the regular expression match whatever is inside and indicate the start and end of a group.

The group’s contents can still be retrieved after the match.

Even though we split the string on one or more digits, we still include the
digits in the result.

The \d character matches the digits [0-9] (and many other digit characters).

The + matches the preceding regular expression 1 or more times.

In other words, we match one or more digits using a group and still include them in the list of strings.

如果您的字符串以数字开头并以字符结尾,这种方法也适用。

主程序
import re my_str = '123hello' my_list = list(filter(None, re.split(r'(\d+)', my_str))) # 👇️ ['123', 'hello'] print(my_list)

如果我们不使用该filter()函数,我们将在列表的开头有一个空字符串元素。

请注意,该filter函数返回一个过滤器对象(不是列表)。如果需要将filter对象转换为列表,请将其传递给list()类。