We can use the .split(separator) function to divide a string into a list of strings using a specified separator. The separator tells Python where to break the string. If no separator is specified, then Python will use the white space in the string as the separation point.
See the below example, which breakdowns a string of text into individual words:
my_text = ‘I am learning Python!’
words = my_text.split() #splits the text wherever there is a space.
print(words)
The above program produces the following output:
[‘I’, ‘am’, ‘learning’, ‘Python!’]
Another example to split a string into list with separator ‘-’:
my_string = ‘abcd-efgh-ijkl’
my_list = my_string.split(‘-’)
#split the text wherever there’s a hyphen(‘-')
print(my_list)
Output:
[‘abcd’, ‘efgh’, ‘ijkl’]
The strip() method removes any leading (at the beginning) and trailing (at the end) characters in a string (by default, space is the character).
For example,
text = “ programming “
my_text = text.strip()
#Removes the spaces at the beginning and at the end of the string.
print(my_text)
The output displays the string without those extra spaces at the beginning and at the end:
programming
The Python map() function is used to return a list of results after applying a given function to each item of an iterable(list, tuple etc).
Let’s look at an example:
Getting a list of numbers as input from user using the map() function:
x = list(map(int,input(“Enter the elements“).strip().split(‘ ‘)))
# Reads number inputs from user using map() function
print("List is — “, x)
Output:
Enter the elements: 10 20 30 40
List is — [10, 20, 30, 40]
You will find this function most useful in a competitive coding environment.
#python-programming #computer-science #python #programming