Trim a string in Python
In this tutorial, I’ll explain to you how you can trim a String in Python.
String in Python:
As you already know that it’s an easy task to work with string in Python.
A string is immutable means it’s is always unchangeable and unmodifiable means we can’t change or modify a string after its declaration.
We can declare a string in Python as below:-
s="Hello World" print(s)
Output:
Hello World
To trim a String in Python:
Trimming a string means we have to remove all the white-spaces present in the string.
Suppose we have s=” Hello” here you can see in from of Hello after double quotes we have some extra spaces so to remove this extra space we use a term called trim.
strip() in Python:
Now to trim a string in Python we can use an in-built Python function called strip() it has various other applications but we can use it to trim a string in Python.
strip() in Python returns a copy of a string with the leading and trailing characters removed if the characters are none it removed white spaces.
We use strip() function as below:-
s = " Hello World" print(s) #it will print Hello World including white spaces #Now to remove white paces we'll use strip function print(s.strip()) #it will print Hello World without white spaces
Output:-
Hello World Hello World
For more information about strip() refer to the python.org documentation.
Leave a Reply