Removing whitespace from strings in a list
This Python code takes a list of strings and creates a new list called trimmed, where leading and trailing whitespace (including spaces, tabs, and newline characters) is removed from each string. Here's how the code works:
- strings = [" hello ", " world ", " python "]: This line initializes a variable named strings and assigns it a list containing three strings, each of which has leading and trailing whitespace.
- trimmed = [string.strip() for string in strings] : This line of code initializes a variable named trimmed and assigns it the result of a list comprehension.
- for string in strings: This part sets up a loop that iterates through each string string in the strings list.
- string.strip(): For each string in the list, the strip() method is called to remove leading and trailing whitespace from the string. The result is a string with whitespace removed.
- [string.strip() for string in strings]: This is the list comprehension itself. It iterates through the strings in the strings list, removes whitespace from each string, and includes the modified strings in the new list.
- print(strings): This line of code prints the original strings list to the console.
- print(trimmed): This line of code prints the trimmed list (which contains the modified strings with leading and trailing whitespace removed) to the console.
Source Code
strings = [" hello ", " world ", " python "]
trimmed = [string.strip() for string in strings]
print(strings)
print(trimmed)
Output
[' hello ', ' world ', ' python ']
['hello', 'world', 'python']