|
| 1 | +--- |
| 2 | +Title: '.removesuffix()' |
| 3 | +Description: 'Returns a copy of a string with the specified suffix removed, if present.' |
| 4 | +Subjects: |
| 5 | + - 'Code Foundations' |
| 6 | + - 'Computer Science' |
| 7 | +Tags: |
| 8 | + - 'Methods' |
| 9 | + - 'Strings' |
| 10 | +CatalogContent: |
| 11 | + - 'learn-python-3' |
| 12 | + - 'paths/computer-science' |
| 13 | +--- |
| 14 | + |
| 15 | +The **`str.removesuffix()`** method returns a new string with the specified suffix removed, if present. If the string does not end with the given suffix, the original string is returned unchanged. This method is case-sensitive and does not modify the original string. |
| 16 | + |
| 17 | +## Syntax |
| 18 | + |
| 19 | +```pseudo |
| 20 | +string_name.removesuffix(suffix) |
| 21 | +``` |
| 22 | + |
| 23 | +**Parameters:** |
| 24 | + |
| 25 | +- `suffix`: The string to remove from the end of the original string. |
| 26 | + |
| 27 | +**Return value:** |
| 28 | + |
| 29 | +A new string with the suffix removed if it exists, otherwise, the original string. |
| 30 | + |
| 31 | +## Example 1: Removing a file extension |
| 32 | + |
| 33 | +This method can be used to remove a file extension when the suffix matches exactly: |
| 34 | + |
| 35 | +```py |
| 36 | +file_type = "Cat Store.docx" |
| 37 | +result = file_type.removesuffix('.docx') |
| 38 | +print(result) |
| 39 | +``` |
| 40 | + |
| 41 | +The output would look like this: |
| 42 | + |
| 43 | +```shell |
| 44 | +Cat Store |
| 45 | +``` |
| 46 | + |
| 47 | +## Example 2: Case sensitivity |
| 48 | + |
| 49 | +`.removesuffix()` is case-sensitive, so, if the case does not match exactly, the suffix is not removed: |
| 50 | + |
| 51 | +```py |
| 52 | +statement = "And when I silently snuck up on my mom, I jumped up and exclaimed 'BOO!'" |
| 53 | +result = statement.removesuffix('Boo!') |
| 54 | +print(result) |
| 55 | +``` |
| 56 | + |
| 57 | +Here's the output: |
| 58 | + |
| 59 | +```shell |
| 60 | +And when I silently snuck up on my mom, I jumped up and exclaimed 'BOO!' |
| 61 | +``` |
| 62 | + |
| 63 | +## Example 3: Removing text from a sentence |
| 64 | + |
| 65 | +The suffix must match the exact ending of the string, including punctuation: |
| 66 | + |
| 67 | +```py |
| 68 | +quote = 'Do or do not, there is no try (Yoda).' |
| 69 | +result = quote.removesuffix(' (Yoda).') |
| 70 | +print(result) |
| 71 | +``` |
| 72 | + |
| 73 | +The output for this code would look like this: |
| 74 | + |
| 75 | +```shell |
| 76 | +Do or do not, there is no try |
| 77 | +``` |
0 commit comments