Reference Materials
Created with over a decade of experience.
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python String Methods
- Python String capitalize()
- Python String center()
- Python String casefold()
- Python String count()
- Python String endswith()
- Python String expandtabs()
- Python String encode()
- Python String find()
- Python String format()
- Python String index()
- Python String isalnum()
- Python String isalpha()
- Python String isdecimal()
- Python String isdigit()
- Python String isidentifier()
- Python String islower()
- Python String isnumeric()
- Python String isprintable()
- Python String isspace()
- Python String istitle()
- Python String isupper()
- Python String join()
- Python String ljust()
- Python String rjust()
- Python String lower()
- Python String upper()
- Python String swapcase()
- Python String lstrip()
- Python String rstrip()
- Python String strip()
- Python String partition()
- Python String maketrans()
- Python String rpartition()
- Python String translate()
- Python String replace()
- Python String rfind()
- Python String rindex()
- Python String split()
- Python String rsplit()
- Python String splitlines()
- Python String startswith()
- Python String title()
- Python String zfill()
- Python String format_map()
Python String strip()
The strip() method removes any leading (starting) and trailing (ending) whitespaces from a given string.
Example
message = ' Learn Python '
# remove leading and trailing whitespaces
print(message.strip())
# Output: Learn Python
String strip() Syntax
string.strip([chars])
strip() Arguments
The method takes an optional parameter - chars:
- chars - specifies the set of characters to be removed from both the left and right parts of a string
Note: If the chars argument is not provided, all leading and trailing whitespaces are removed from the string.
strip() Return Value
The method returns a string after removing both leading and trailing spaces/characters.
Example 1: Remove Whitespaces From String
string = ' xoxo love xoxo '
# leading and trailing whitespaces are removed
print(string.strip())
Output
xoxo love xoxo
Example 2: Remove Characters From String
string = ' xoxo love xoxo '
# all <whitespace>,x,o,e characters in the left
# and right of string are removed
print(string.strip(' xoe'))
Output
lov
Notes:
- Removes characters from the left until a mismatch occurs with the characters in the
charsargument. - Removes characters from the right until a mismatch occurs with the characters in the
charsargument.
Example 3: Remove Newline With strip()
We can also remove newlines from a string using the strip() method. For example,
string = '\nLearn Python\n'
print('Original String: ', string)
new_string = string.strip()
print('Updated String:', new_string)
Output
Original String: Learn Python Updated String: Learn Python
Also Read:
Did you find this article helpful?
