Detect spaces at the start of a string and remove those in Python
In this content, we will learn how to detect spaces at the start of the string and remove those spaces in Python.
Introduction
In Python, sometimes we might have problem in string in which we need to check if string has spaces are not. Those spaces are called whitespaces or blank spaces. To detect those spaces we have so many methods present. After finding those spaces we need to remove them. Let’s discuss certain ways to detect and remove the spaces.
Python string:
In Python, a string is a sequence of characters. It is an immutable data type, it means the string cannot be changed after creation. We use single or double quotes to represent a string in Python.
Methods for detecting spaces:
You can detect spaces at the start of string by using following methods:
#Method 1: ‘startswith()’
text = " Good, Morning!" if text.startswith(" "): print("String starts with a space.") else: print("String does not start with a space.")
output:
String starts with a space.
#Method 2: Using indexing
string = " Good, morning!" if string[0] == " ": print("String starts with a space.") else: print("String does not start with a space.")
output:
String starts with a space.
#Method 3: Using slicing
string = " Good" if string[:1] == " ": print("String starts with a space.") else: print("String does not start with a space.")
output:
String starts with a space.
Method for removing spaces:
You can remove spaces at the start of string by using following methods:
#Method 1: ‘strip()’
string =" Good" result = string.lstrip() print(result)
output:
Good
#Method 2: Using slicing
string = " Good" result = string[len(string) - len(string.lstrip()):] print(result)
output:
Good
These methods effectively helps us to detect and remove spaces at the start of the string and you can choose the one that fits your requirements and coding style.
Leave a Reply