IT, Programming, & Web Development › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 6: Python › CS105: Introduction to Python by Saylor Academy › Unit 4: Data Structures I – Lists and Strings › Removing specific characters with strip
- This topic is empty.
-
AuthorPosts
-
August 22, 2024 at 5:58 am #3259
Removing specific characters with strip
byu/DigitalSplendid inlearnpython\
Python’s
strip()
andsplit()
methods with examplesSource: Created with the help of ChatGPT
The
strip()
andsplit()
methods in Python are string manipulation functions often used to clean and process textual data.1.
strip()
The
strip()
method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (by default, whitespace characters) from a string. It does not remove spaces inside the string.Syntax:
string.strip([chars])
- chars (optional): Specifies the set of characters to be removed. If omitted, the method will remove whitespace by default.
Example:
# Example 1: Using strip with default whitespace removal text = " Hello, World! " stripped_text = text.strip() print(stripped_text) # Output: "Hello, World!" # Example 2: Removing specific characters text = "///Python///" stripped_text = text.strip("/") print(stripped_text) # Output: "Python"
2.
split()
The
split()
method breaks a string into a list of substrings based on a specified separator. If no separator is specified, it defaults to splitting at any whitespace (spaces, tabs, or newlines).Syntax:
string.split([separator, maxsplit])
- separator (optional): The delimiter string where the split occurs. If omitted, any whitespace is considered a separator.
- maxsplit (optional): The maximum number of splits to do. The default is
-1
, which means “all occurrences.”
Example:
# Example 1: Splitting a string with default separator (whitespace) text = "Hello, World!" split_text = text.split() print(split_text) # Output: ['Hello,', 'World!'] # Example 2: Splitting a string with a specified separator text = "apple,banana,orange" split_text = text.split(',') print(split_text) # Output: ['apple', 'banana', 'orange'] # Example 3: Limiting the number of splits text = "apple,banana,orange,grape" split_text = text.split(',', 2) print(split_text) # Output: ['apple', 'banana', 'orange,grape']
Combined Example:
You can combine both
strip()
andsplit()
to clean and process data more effectively:text = " apple, banana, orange " cleaned_text = text.strip().split(", ") print(cleaned_text) # Output: ['apple', 'banana', 'orange']
Here,
strip()
removes leading and trailing spaces, andsplit()
divides the string into a list of fruits based on the separator", "
. -
AuthorPosts
- You must be logged in to reply to this topic.