split string in python

24

text= 'Love thy neighbor'

# splits at space
print(text.split())

grocery = 'Milk, Chicken, Bread'

# splits at ','
print(grocery.split(', '))

# Splits at ':'
print(grocery.split(':'))

"""
Output

['Love', 'thy', 'neighbor']
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']
"""
s = 'KDnuggets is a fantastic resource'

print(s.split())

# Output

# ['KDnuggets', 'is', 'a', 'fantastic', 'resource']


# By default, split() splits on whitespace,
# but other character(s) sequences can be passed in as well.

s = 'these,words,are,separated,by,comma'
print('\',\' separated split -> {}'.format(s.split(',')))

s = 'abacbdebfgbhhgbabddba'
print('\'b\' separated split -> {}'.format(s.split('b')))


# ',' separated split -> ['these', 'words', 'are', 'separated', 'by', 'comma']
# 'b' separated split -> ['a', 'ac', 'de', 'fg', 'hhg', 'a', 'dd', 'a']

Comments

Submit
0 Comments