Use percent-encoding to quote a string, omitting existing '%xx' escape sequences. See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1 * `string`: The string to be percent-escaped. * `safe`: A string containing characters that may be treated as safe, and do not need to
(string: str, safe: str)
| 495 | |
| 496 | |
| 497 | def quote(string: str, safe: str) -> str: |
| 498 | """ |
| 499 | Use percent-encoding to quote a string, omitting existing '%xx' escape sequences. |
| 500 | |
| 501 | See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1 |
| 502 | |
| 503 | * `string`: The string to be percent-escaped. |
| 504 | * `safe`: A string containing characters that may be treated as safe, and do not |
| 505 | need to be escaped. Unreserved characters are always treated as safe. |
| 506 | See: https://www.rfc-editor.org/rfc/rfc3986#section-2.3 |
| 507 | """ |
| 508 | parts = [] |
| 509 | current_position = 0 |
| 510 | for match in re.finditer(PERCENT_ENCODED_REGEX, string): |
| 511 | start_position, end_position = match.start(), match.end() |
| 512 | matched_text = match.group(0) |
| 513 | # Add any text up to the '%xx' escape sequence. |
| 514 | if start_position != current_position: |
| 515 | leading_text = string[current_position:start_position] |
| 516 | parts.append(percent_encoded(leading_text, safe=safe)) |
| 517 | |
| 518 | # Add the '%xx' escape sequence. |
| 519 | parts.append(matched_text) |
| 520 | current_position = end_position |
| 521 | |
| 522 | # Add any text after the final '%xx' escape sequence. |
| 523 | if current_position != len(string): |
| 524 | trailing_text = string[current_position:] |
| 525 | parts.append(percent_encoded(trailing_text, safe=safe)) |
| 526 | |
| 527 | return "".join(parts) |
no test coverage detected