@@ -8,32 +8,34 @@ use crate::Locator;
88use crate :: { checkers:: ast:: Checker , settings:: types:: PythonVersion } ;
99
1010/// ## What it does
11- /// Checks for the removal of a prefix or suffix from a string by assigning
12- /// the string to a slice after checking `.startswith()` or `.endswith()`, respectively.
11+ /// Checks for code that could be written more idiomatically using
12+ /// [`str.removeprefix()`](https://docs.python.org/3/library/stdtypes.html#str.removeprefix)
13+ /// or [`str.removesuffix()`](https://docs.python.org/3/library/stdtypes.html#str.removesuffix).
14+ ///
15+ /// Specifically, the rule flags code that conditionally removes a prefix or suffix
16+ /// using a slice operation following an `if` test that uses `str.startswith()` or `str.endswith()`.
17+ ///
18+ /// The rule is only applied if your project targets Python 3.9 or later.
1319///
1420/// ## Why is this bad?
15- /// The methods [`str.removeprefix`](https://docs.python.org/3/library/stdtypes.html#str.removeprefix)
16- /// and [`str.removesuffix`](https://docs.python.org/3/library/stdtypes.html#str.removesuffix),
17- /// introduced in Python 3.9, have the same behavior
18- /// and are more readable and efficient.
21+ /// The methods [`str.removeprefix()`](https://docs.python.org/3/library/stdtypes.html#str.removeprefix)
22+ /// and [`str.removesuffix()`](https://docs.python.org/3/library/stdtypes.html#str.removesuffix),
23+ /// introduced in Python 3.9, have the same behavior while being more readable and efficient.
1924///
2025/// ## Example
2126/// ```python
22- /// filename[:-4] if filename.endswith(".txt") else filename
23- /// ```
27+ /// def example( filename: str, text: str):
28+ /// filename = filename[:-4] if filename.endswith(".txt") else filename
2429///
25- /// ```python
26- /// if text.startswith("pre"):
27- /// text = text[3:]
30+ /// if text.startswith("pre"):
31+ /// text = text[3:]
2832/// ```
2933///
3034/// Use instead:
3135/// ```python
32- /// filename = filename.removesuffix(".txt")
33- /// ```
34- ///
35- /// ```python
36- /// text = text.removeprefix("pre")
36+ /// def example(filename: str, text: str):
37+ /// filename = filename.removesuffix(".txt")
38+ /// text = text.removeprefix("pre")
3739/// ```
3840#[ derive( ViolationMetadata ) ]
3941pub ( crate ) struct SliceToRemovePrefixOrSuffix {
@@ -46,10 +48,10 @@ impl AlwaysFixableViolation for SliceToRemovePrefixOrSuffix {
4648 fn message ( & self ) -> String {
4749 match self . affix_kind {
4850 AffixKind :: StartsWith => {
49- "Prefer `removeprefix` over conditionally replacing with slice." . to_string ( )
51+ "Prefer `str. removeprefix() ` over conditionally replacing with slice." . to_string ( )
5052 }
5153 AffixKind :: EndsWith => {
52- "Prefer `removesuffix` over conditionally replacing with slice." . to_string ( )
54+ "Prefer `str. removesuffix() ` over conditionally replacing with slice." . to_string ( )
5355 }
5456 }
5557 }
0 commit comments