# SplittingAtoms.py Copyright (c) Kari Laitinen # http://www.naturalprogramming.com # 2006-05-24 File created. # 2022-12-16 Converted to Python 3. # This program demonstrates how simple regular expressions can # be used to split strings. import re # regular expressions module atomic_text = "\n Atoms consist of protons, neutrons, and electrons." print( atomic_text ) # Split the atomic text in positions that contain a newline or a comma. substrings_from_text = re.split( "[\n,]", atomic_text ) for substring_index in range( len( substrings_from_text ) ) : print( "\n %d:%s" % ( substring_index, substrings_from_text[ substring_index ] ), end="" ) # The following statement rejoins the strings from the list referenced # by substrings_from_text. After this the string will be resplit. atomic_text = "".join( substrings_from_text ) print( "\n\n" + atomic_text ) # Split the atomic text in positions that contain a space character. substrings_from_text = re.split( "[ ]", atomic_text ) for substring_index in range( len( substrings_from_text ) ) : print( "\n %d:%s" % ( substring_index, substrings_from_text[ substring_index ] ), end="" ) print( "\n" )