Sunday, July 24, 2022

Converting List to strings and vice versa?

The string is a sequence of characters while a list is a sequence of values. To convert from a string to a list of characters you need to apply the list function to a string. In general form this can be written as:
string_name = "string"
t = list(string_name)
print("t = {}".format(t))
t = ['s','t','r','i','n','g']
As seen the list function breaks a string into individual letters. To break the string into words, the split function is used.
Example 2 Create a program where the user manually enters a sentence (string) which is broken into words using the split function.
Solution: Using input built-in function the user will provide a string which will be saved under USER_INPUT variable name. If you type EXIT it will quit the execution of the program. If the user typed string is longer than 20 characters it will perform the rest of the program (split the string onto words in a list and print the list). Otherwise, it will print the string to type another string.
while True:
USER_INPUT = input("Enter a sentence (Type EXIT to quit): ")
if USER_INPUT == "EXIT":break
if len(USER_INPUT) > 20:
t = USER_INPUT.split()
print("t = {}".format(t))
break
else:
print("The sencetence is too short, type another one.)")
The first outcome of the program will be to type the "EXIT" when the message "Enter a sentence (Type EXIT to quit): ".
Enter a sentence (Type EXIT to quit): EXIT
The second outcome is to type a string that is longer than 20 characters.
Enter a sentence (Type EXIT to quit): Your eyes can deceive you; don't trust them.
t = ['Your', 'eyes', 'can', 'deceive', 'you;', 'don't', 'trust', 'them.']
As you can see the split function will split the string onto individual words. Join is the inverse built-in function of the split. It takes a list of strings and concatenates the elements. In the next example, we will join the words stored in the list into one string.
Example 3 Concatenate the list elements of the list ["This", "is", "my", "life"] into one string using built-in join function.
Solution
Lst1 = ["This", "is", "my", "life"]
delimiter = ' '
solution = delimiter.join(Lst1)
print("solution = {}".format(solution))
The previous code will generate the following output.
solution = This is my life

No comments:

Post a Comment