Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

python - Product code looks like abcd2343, what to split by letters and numbers

I have a list of product codes in a text file, on each like is the product code that looks like:

abcd2343 abw34324 abc3243-23A

So it is letters followed by numbers and other characters.

I want to split on the first occurrence of a number.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
In [32]: import re

In [33]: s='abcd2343 abw34324 abc3243-23A'

In [34]: re.split('(d+)',s)
Out[34]: ['abcd', '2343', ' abw', '34324', ' abc', '3243', '-', '23', 'A']

Or, if you want to split on the first occurrence of a digit:

In [43]: re.findall('d*D+',s)
Out[43]: ['abcd', '2343 abw', '34324 abc', '3243-', '23A']

  • d+ matches 1-or-more digits.
  • d*D+ matches 0-or-more digits followed by 1-or-more non-digits.
  • d+|D+ matches 1-or-more digits or 1-or-more non-digits.

Consult the docs for more about Python's regex syntax.


re.split(pat, s) will split the string s using pat as the delimiter. If pat begins and ends with parentheses (so as to be a "capturing group"), then re.split will return the substrings matched by pat as well. For instance, compare:

In [113]: re.split('d+', s)
Out[113]: ['abcd', ' abw', ' abc', '-', 'A']   # <-- just the non-matching parts

In [114]: re.split('(d+)', s)
Out[114]: ['abcd', '2343', ' abw', '34324', ' abc', '3243', '-', '23', 'A']  # <-- both the non-matching parts and the captured groups

In contrast, re.findall(pat, s) returns only the parts of s that match pat:

In [115]: re.findall('d+', s)
Out[115]: ['2343', '34324', '3243', '23']

Thus, if s ends with a digit, you could avoid ending with an empty string by using re.findall('d+|D+', s) instead of re.split('(d+)', s):

In [118]: s='abcd2343 abw34324 abc3243-23A 123'

In [119]: re.split('(d+)', s)
Out[119]: ['abcd', '2343', ' abw', '34324', ' abc', '3243', '-', '23', 'A ', '123', '']

In [120]: re.findall('d+|D+', s)
Out[120]: ['abcd', '2343', ' abw', '34324', ' abc', '3243', '-', '23', 'A ', '123']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...