Att String Rstrip
## Python String rstrip() Method
The `rstrip()` method returns a copy of the string with trailing characters removed. By default, it removes all trailing whitespace characters (such as spaces, newlines, carriage returns, and tabs). You can also specify a custom set of characters to be stripped from the end of the string.
---
## Syntax
The syntax for the `rstrip()` method is as follows:
```python
str.rstrip()
```
### Parameters
* **`chars`** *(Optional)*: A string specifying the set of characters to be removed from the end of the string. If omitted or `None`, the method defaults to removing all whitespace characters.
### Return Value
* Returns a **new string** with the specified trailing characters removed. The original string remains unmodified because Python strings are immutable.
---
## Code Examples
Here are practical examples demonstrating how to use the `rstrip()` method in different scenarios.
### Example 1: Basic Usage and Custom Character Stripping
```python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
random_string = 'this is good '
# 1. Default behavior: Trailing spaces are removed
print(random_string.rstrip())
# 2. 'si oo' is not at the very end of the string (due to trailing spaces), so nothing is removed
print(random_string.rstrip('si oo'))
# 3. In 'sid oo', 'd oo' matches the trailing characters (including spaces), so 'ood' is stripped
print(random_string.rstrip('sid oo'))
# 4. Strip 'm' and '/' from the end of a URL. Note that '.' is not removed because it is not at the end after 'm/' is stripped
website = 'www.runoob.com/'
print(website.rstrip('m/.'))
# 5. Remove trailing commas (,), periods (.), and letters 's', 'q', or 'w'
txt = "banana,,,,,ssqqqww....."
x = txt.rstrip(",.qsw")
print(x)
# 6. Remove trailing asterisks (*)
str_example = "*****this is string example....wow!!!*****"
print(str_example.rstrip('*'))
```
### Output
```text
this is good
this is good
this is g
www.runoob.co
banana
*****this is string example....wow!!!
```
---
## Important Considerations
### 1. Character Set Matching (Not Substring Matching)
The `chars` argument is **not** a prefix or a substring; instead, it is treated as a set of individual characters. The method will keep stripping characters from the right side of the string as long as they match any character in the provided `chars` set.
For example:
```python
text = "link_123"
# This will strip '3', '2', and '1' because they are all present in the set "1234"
print(text.rstrip("1234")) # Output: "link_"
```
### 2. Whitespace Characters Removed by Default
When no argument is passed, `rstrip()` removes all of the following standard ASCII whitespace characters:
* Space (`' '`)
* Newline (`'\n'`)
* Carriage return (`'\r'`)
* Horizontal tab (`'\t'`)
* Vertical tab (`'\v'`)
* Form feed (`'\f'`)
### 3. String Immutability
Since strings in Python are immutable, `rstrip()` does not modify the original string in place. It always returns a newly created string.
YouTip