Appearance
Remove final character from string
You can remove the final character from a string in Python using string slicing. For example, if you have a string called "string" and you want to remove the last character, you can use the following code snippet:
Remove final character from string in Python
python
string = string[:-1]This creates a new string that is a slice of the original string, starting from the first character (0th index) and going up to the second-to-last character.
For example,
Example of remove final character from a string in Python
python
string = "Hello World"
string = string[:-1]
print(string)This will output:
console
Hello WorlYou can also use string slicing to remove multiple characters from the end of a string. For example, to remove the last two characters of a string, you can use the following code snippet:
Remove multiple characters from the end of a string in Python
python
string = string[:-2]Another way to remove the last character from a string is using the rstrip() method. Note that rstrip() removes all trailing occurrences of the specified character(s), not just the last one.
Example of removing a trailing character with rstrip() in Python
python
string = "Hello World"
string = string.rstrip('d')
print(string)It will output:
console
Hello WorlFor Python 3.9+, you can also use the removesuffix() method, which safely removes a specific trailing substring without affecting other occurrences:
Example of removing a trailing character with removesuffix() in Python
python
string = "Hello World"
string = string.removesuffix('d')
print(string)It will output:
console
Hello Worl