Remove first character from a Python string
This post will discuss how to remove the first character from a string in Python.
1. Using Slicing
A simple approach to remove the first character from a string is with slicing. Here’s how the code would look like:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = '!Hello' s = s[1:] print(s) # Hello |
If you want to remove the first n characters, you can do:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = '!!Hello' n = 2 s = s[n:] print(s) # Hello |
If you want to remove a character at a specific position, you can do:
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = '!Hello' pos = 2 s = s[0:pos] + s[pos+1:] print(s) # !Hllo |
2. Using split() function
If you need to remove the first occurrence of the given character, you can use the split function with join. This would translate to a simple code below:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = '!Hello!' ch = '!' s = ''.join(s.split(ch, 1)) print(s) # Hello! |
3. Using lstrip() function
If you need to remove all occurrence of a leading character, you can use the lstrip function:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = '!!Hello!' ch = '!' s = s.lstrip(ch) print(s) # Hello! |
That’s all about removing the first character from a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)