How to split a string into words in Python

4 Answers

0 votes
s = 'python programming language'

words = s.split(" ")

for w in words:
    print(w)


'''
run:

python
programming
language

'''

 



answered Feb 5, 2017 by avibootz
edited Aug 29 by avibootz
0 votes
import re

def SplitString(s):
    # Split on any sequence of non‑word characters
    # \W matches anything except letters, digits, and underscore
    return [token for token in re.split(r"\W+", s) if token]

s = "-c, c++.. c#:: -java ,php...python"

tokens = SplitString(s)

for t in tokens:
    print(t)

 
'''
run:
 
c
c
c
java
php
python
 
'''

 



answered Feb 5, 2017 by avibootz
edited Aug 29 by avibootz
0 votes
import re
 
def SplitString(s, delims):
    # delims is a regex character class, e.g. "[ ,.:\\-!]+"
    tokens = re.split(delims, s)
     
    return [t for t in tokens if t]
 
s = "-c, c++.. c#:: -java ,php...python    go!"
delims = r"[ ,.:\-!]+"
 
tokens = SplitString(s, delims)
 
for t in tokens:
    print(t)
 
  
'''
run:
  
c
c++
c#
java
php
python
go
  
'''

 



answered Feb 5, 2017 by avibootz
edited Aug 29 by avibootz
0 votes
def split_string(s: str, delims: str) -> list[str]:
    delim_set: set[str] = set(delims)

    normalized: str = "".join(" " if ch in delim_set else ch for ch in s)

    return [t for t in normalized.split() if t]


s: str = "-c, c++.. c#:: -java! ,php...python:      go!"
delims: str = " ,.:\\-!"

tokens: list[str] = split_string(s, delims)

for t in tokens:
    print(t)


'''
run:

c
c++
c#
java
php
python
go

'''

 



answered Aug 29 by avibootz
...