The major difference between strip and split method is that strip method removes specified characters from both ends of a string. By default it removes whitespace and returns a single modified string. Whereas, split method divides a string into parts based on a specified delimiter and by default it splits by whitespace and returns a list of strings.
Example of strip()
s = " hello world "
# Removes spaces from both ends
print(s.strip())
s1 = "***hello***"
# Removes asterisks from both ends
print(s1.strip("*"))
Output
hello world hello
Explanation:
- s.strip() removes spaces from both beginning and end of the string and results in "hello world".
- strip("*") removes * characters from both ends and results in "hello".
Example of split()
s = "hello world"
# Splits by whitespace
print(s.split())
s1 = "apple,orange,banana"
# Splits by comma
print(s1.split(','))
Output
['hello', 'world'] ['apple', 'orange', 'banana']
Explanation:
- s.split() basically splits "hello world" into two elements based on whitespace and results in ['hello', 'world']
- split(',') divides string at each comma and results in list ['apple', 'orange', 'banana']