In Python, you can remove leading and trailing characters (or a substring) from a string using the strip() method. The strip() method takes an optional argument that specifies the characters (or substring) to remove from the string. If no argument is provided, it removes whitespace characters (i.e., spaces, tabs, and newlines).
Here's an example of stripping characters from a string using the strip() method:
text = " This is a sentence with leading and trailing spaces. \t\n"# Strip leading and trailing spaces, tabs, and newlines from the stringstripped_text = text.strip()# Print the stripped stringprint(stripped_text) |
Output:
This is a sentence with leading and trailing spaces. |
In this example, we have a string text with leading and trailing spaces, tabs, and newlines. We use the strip() method to remove these characters from the string, and assign the resulting stripped string to the variable stripped_text. We then print the stripped string to the console.
You can also specify a custom character (or substring) to remove from the string. Here's an example:
text = "***This is a sentence with asterisks to be removed.***"# Strip leading and trailing asterisks from the stringstripped_text = text.strip("*")# Print the stripped stringprint(stripped_text) |
Output:
This is a sentence with asterisks to be removed. |
In this example, we have a string text with leading and trailing asterisks. We use the strip() method to remove these asterisks from the string by specifying the character * as the argument to the strip() method, and assign the resulting stripped string to the variable stripped_text. We then print the stripped string to the console.