Skip to content

Commit 005cbc1

Browse files
kana800BethanyG
authored andcommitted
added removeprefix and removesuffix
1 parent 6f841fb commit 005cbc1

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

concepts/string-methods/about.md

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ The code points specified in `<chars>` are not a prefix or suffix - **all combin
8585

8686
>>> ' unaddressed '.strip('dnue ')
8787
'address'
88-
```
88+
```
8989

9090

9191
[`<str>.replace(<substring>, <replacement substring>)`][str-replace] returns a copy of the string with all occurrences of `<substring>` replaced with `<replacement substring>`.
@@ -115,6 +115,29 @@ Just the place for a Snark! I have said it thrice:
115115
'book keeper'
116116
```
117117

118+
:star:**Newly added in Python `3.9`**
119+
120+
Python `3.9` introduces two new string methods that make removing prefixes and suffixes much easier.
121+
122+
[`<str>.removeprefix(<substring>)`](https://docs.python.org/3.9/library/stdtypes.html#str.removeprefix) return the string without the prefix (`string[len(<substring>):]`), if the `<substring>` isn't present it will return a copy of the original string.
123+
124+
```python
125+
# removing a prefix
126+
>>> 'TestHook'.removeprefix('Test')
127+
'Hook'
128+
>>> 'bookkeeper'.removeprefix('book')
129+
'bookkeeper'
130+
```
131+
132+
[`<str>.removesuffix(<substring>)`](https://docs.python.org/3.9/library/stdtypes.html#str.removesuffix) return the string without the suffix (`string[:-len(substring)]`), if the `<substring>` isn't present it will return a copy of the original string.
133+
134+
```python
135+
# removing a suffix
136+
>>> 'TestHook'.removesuffix('Test')
137+
'Test'
138+
>>> 'bookkeeper'.removesuffix('keeper')
139+
'bookkeeper'
140+
```
118141

119142
For more examples and methods the [informal tutorial][informal tutorial] is a nice jumping-off point.
120143
[How to Unicode][howto unicode] in the Python docs offers great detail on Unicode, encoding, bytes, and other technical considerations for working with strings in Python.

0 commit comments

Comments
 (0)