SoFunction
Updated on 2024-11-13

Python cookbook (Strings and Text) Splitting Strings for Any Number of Delimiters Examples

This article example describes Python for any number of separator split string operation. Shared for your reference, as follows:

Question:Splits strings with inconsistent separators (and spaces between separators) into separate fields;

Solution:Use the more flexible () method, which allows you to specify multiple patterns for the separator.

Description:The string object's split() can only handle simple cases, and it doesn't support multiple separators, and it can't do anything about spaces that might be around the separator.

# 
#
# Example of splitting a string on multiple delimiters using a regex
import re #Import the regular expression module
line = 'asdf fjdk; afed, fjek,asdf,   foo'
# (a) Splitting on space, comma, and semicolon
parts = (r'[;,\s]\s*', line)
print(parts)
# (b) The use of "capture groups" in regular expression patterns requires attention to be paid to whether or not the capture groups are enclosed in parentheses, as the use of capture groups results in the matched text also being included in the final result
fields = (r'(;|,|\s)\s*', line)
print(fields)
# (c) Improvement of string output based on the delimiter character above
values = fields[::2]
delimiters = fields[1::2]
('')
print('value =', values)
print('delimiters =', delimiters)
newline = ''.join(v+d for v,d in zip(values, delimiters))
print('newline =', newline)
# (d) Use of non-capture groups (? :...) to group regular expression patterns in parentheses without outputting separators.
parts = (r'(?:,|;|\s)\s*', line)
print(parts)

>>> ================================ RESTART ================================
>>>
['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']
['asdf', ' ', 'fjdk', ';', 'afed', ',', 'fjek', ',', 'asdf', ',', 'foo']
value = ['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']
delimiters = [' ', ';', ',', ',', ',', '']
newline = asdf fjdk;afed,fjek,asdf,foo
['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']
>>>

(Code taken from thePython Cookbook》)

PS: Here are 2 more very convenient regular expression tools for your reference:

JavaScript regular expression online test tool:
http://tools./regex/javascript

Regular expression online generation tool:
http://tools./regex/create_reg

Readers interested in more Python related content can check out this site's topic: thePython Regular Expression Usage Summary》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques

I hope the description of this article will help you in Python programming.