Frequently Asked Questions

Explain split() and join() functions in Python?

split()

The split() function is used to break a string by a specified separator (default is space) and returns a list of strings.

# Split a string by blank space (this is the default)

a="Hello, My Name is Varsha. I am a Data Scientist."

a.split()

[‘Hello,’, ‘My’, ‘Name’, ‘is’, ‘Varsha.’, ‘I’, ‘am’, ‘a’, ‘Data’, ‘Scientist.’]
# Split by a specific element (doesn't include the element that was split on)

b="Hello, My Name is Varsha. I am a Data Scientist."

b.split('a')

[‘Hello, My N’, ‘me is V’, ‘rsh’, ‘. I ‘, ‘m ‘, ‘ D’, ‘t’, ‘ Scientist.’]

join()

The join() function is used to convert the list of elements into a string separated by a specific joining element.

join() method to connect the elements of a sequence into a string.


x=["We","are","learning","Python"]
# join with space in between
" ".join(x)

We are learning Python


x=["We","are","learning","Python"]

# join with - in between
"-".join(x)

We-are-learning-Python

 

 

Other Popular Questions