Use str.removeprefix() and str.removesuffix()

https://docs.python.org/3/whatsnew/3.9.html#new-string-methods-to-remove-prefixes-and-suffixes
This commit is contained in:
Florian Bruhin 2024-10-13 15:28:44 +02:00
parent fe868901ab
commit 4d069b8fc3
19 changed files with 38 additions and 39 deletions

View File

@ -242,7 +242,7 @@ class PACFetcher(QObject):
pac_prefix = "pac+"
assert url.scheme().startswith(pac_prefix)
url.setScheme(url.scheme()[len(pac_prefix):])
url.setScheme(url.scheme().removeprefix(pac_prefix))
self._pac_url = url
with qtlog.disable_qt_msghandler():

View File

@ -418,7 +418,7 @@ def settings(
blink_settings_flag = f'--{_BLINK_SETTINGS}='
for flag in special_flags:
if flag.startswith(blink_settings_flag):
for pair in flag[len(blink_settings_flag):].split(','):
for pair in flag.removeprefix(blink_settings_flag).split(','):
key, val = pair.split('=', maxsplit=1)
result[_BLINK_SETTINGS].append((key, val))

View File

@ -127,7 +127,7 @@ class Completer(QObject):
Return:
([parts_before_cursor], 'part_under_cursor', [parts_after_cursor])
"""
text = self._cmd.text()[len(self._cmd.prefix()):]
text = self._cmd.text().removeprefix(self._cmd.prefix())
if not text or not text.strip():
# Only ":", empty part under the cursor with nothing before/after
return [], '', []

View File

@ -91,10 +91,10 @@ def _qtwebengine_features(
for flag in special_flags:
if flag.startswith(_ENABLE_FEATURES):
flag = flag[len(_ENABLE_FEATURES):]
flag = flag.removeprefix(_ENABLE_FEATURES)
enabled_features += flag.split(',')
elif flag.startswith(_DISABLE_FEATURES):
flag = flag[len(_DISABLE_FEATURES):]
flag = flag.removeprefix(_DISABLE_FEATURES)
disabled_features += flag.split(',')
elif flag.startswith(_BLINK_SETTINGS):
pass

View File

@ -123,7 +123,7 @@ class KeyHintView(QLabel):
).format(
html.escape(prefix),
suffix_color,
html.escape(str(seq)[len(prefix):]),
html.escape(str(seq).removeprefix(prefix)),
html.escape(cmd)
)
text = '<table>{}</table>'.format(text)

View File

@ -11,11 +11,11 @@ from qutebrowser.utils import log, utils
def _get_name(exc: BaseException) -> str:
"""Get a suitable exception name as a string."""
prefixes = ['qutebrowser', 'builtins']
prefixes = ['qutebrowser.', 'builtins.']
name = utils.qualname(exc.__class__)
for prefix in prefixes:
if name.startswith(prefix):
name = name[len(prefix) + 1:]
name = name.removeprefix(prefix)
break
return name

View File

@ -128,7 +128,7 @@ class UrlPattern:
# FIXME This doesn't actually strip the hostname correctly.
if (pattern.startswith('file://') and
not pattern.startswith('file:///')):
pattern = 'file:///' + pattern[len("file://"):]
pattern = 'file:///' + pattern.removeprefix("file://")
return pattern

View File

@ -553,8 +553,8 @@ def same_domain(url1: QUrl, url2: QUrl) -> bool:
if suffix1 != suffix2:
return False
domain1 = url1.host()[:-len(suffix1)].split('.')[-1]
domain2 = url2.host()[:-len(suffix2)].split('.')[-1]
domain1 = url1.host().removesuffix(suffix1).split('.')[-1]
domain2 = url2.host().removesuffix(suffix2).split('.')[-1]
return domain1 == domain2
@ -668,7 +668,7 @@ def parse_javascript_url(url: QUrl) -> str:
urlstr = url.toString(FormatOption.ENCODED)
urlstr = urllib.parse.unquote(urlstr)
code = urlstr[len('javascript:'):]
code = urlstr.removeprefix('javascript:')
if not code:
raise Error("Resulted in empty JavaScript code")

View File

@ -242,7 +242,7 @@ def _get_filename(filename):
os.path.join(os.path.dirname(__file__), '..', '..'))
common_path = os.path.commonprefix([basedir, filename])
if common_path:
filename = filename[len(common_path):].lstrip('/')
filename = filename.removeprefix(common_path).lstrip('/')
return filename

View File

@ -50,7 +50,7 @@ class ConfigChecker(checkers.BaseChecker):
node_str = node.as_string()
prefix = 'config.val.'
if node_str.startswith(prefix):
self._check_config(node, node_str[len(prefix):])
self._check_config(node, node_str.removeprefix(prefix))
def _check_config(self, node, name):
"""Check that we're accessing proper config options."""

View File

@ -114,7 +114,7 @@ def get_all_names():
"""Get all requirement names based on filenames."""
for filename in glob.glob(os.path.join(REQ_DIR, 'requirements-*.txt-raw')):
basename = os.path.basename(filename)
yield basename[len('requirements-'):-len('.txt-raw')]
yield basename.removeprefix('requirements-').removesuffix('.txt-raw')
def run_pip(venv_dir, *args, quiet=False, **kwargs):
@ -231,7 +231,7 @@ def extract_requirement_name(path: pathlib.Path) -> str:
prefix = "requirements-"
assert path.suffix == ".txt", path
assert path.stem.startswith(prefix), path
return path.stem[len(prefix):]
return path.stem.removeprefix(prefix)
def parse_versioned_line(line):
@ -274,11 +274,11 @@ def _get_changes(diff):
continue
elif line.startswith('--- '):
prefix = '--- a/'
current_path = pathlib.Path(line[len(prefix):])
current_path = pathlib.Path(line.removeprefix(prefix))
continue
elif line.startswith('+++ '):
prefix = '+++ b/'
new_path = pathlib.Path(line[len(prefix):])
new_path = pathlib.Path(line.removeprefix(prefix))
assert current_path == new_path, (current_path, new_path)
continue
elif not line.strip():

View File

@ -104,8 +104,7 @@ def update_pdfjs(target_version=None, legacy=False, gh_token=None):
else:
# We need target_version as x.y.z, without the 'v' prefix, though the
# user might give it on the command line
if target_version.startswith('v'):
target_version = target_version[1:]
target_version = target_version.removeprefix('v')
# version should have the prefix to be consistent with the return value
# of get_latest_pdfjs_url()
version = 'v' + target_version

View File

@ -216,22 +216,22 @@ def open_path(quteproc, server, path):
while True:
if path.endswith(new_tab_suffix):
path = path[:-len(new_tab_suffix)]
path = path.removesuffix(new_tab_suffix)
new_tab = True
elif path.endswith(new_bg_tab_suffix):
path = path[:-len(new_bg_tab_suffix)]
path = path.removesuffix(new_bg_tab_suffix)
new_bg_tab = True
elif path.endswith(new_window_suffix):
path = path[:-len(new_window_suffix)]
path = path.removesuffix(new_window_suffix)
new_window = True
elif path.endswith(private_suffix):
path = path[:-len(private_suffix)]
path = path.removesuffix(private_suffix)
private = True
elif path.endswith(as_url_suffix):
path = path[:-len(as_url_suffix)]
path = path.removesuffix(as_url_suffix)
as_url = True
elif path.endswith(do_not_wait_suffix):
path = path[:-len(do_not_wait_suffix)]
path = path.removesuffix(do_not_wait_suffix)
wait = False
else:
break
@ -264,7 +264,7 @@ def run_command(quteproc, server, tmpdir, command):
invalid_tag = ' (invalid command)'
if command.endswith(invalid_tag):
command = command[:-len(invalid_tag)]
command = command.removesuffix(invalid_tag)
invalid = True
else:
invalid = False
@ -639,11 +639,11 @@ def check_open_tabs(quteproc, request, tabs):
while line.endswith(active_suffix) or line.endswith(pinned_suffix):
if line.endswith(active_suffix):
# active
line = line[:-len(active_suffix)]
line = line.removesuffix(active_suffix)
active = True
else:
# pinned
line = line[:-len(pinned_suffix)]
line = line.removesuffix(pinned_suffix)
pinned = True
session_tab = session['windows'][0]['tabs'][i]
@ -739,7 +739,7 @@ def set_up_fileselector(quteproc, py_proc, tmpdir, kind, files, output_type):
tmp_file = None
for i, arg in enumerate(sys.argv):
if arg.startswith('--file='):
tmp_file = arg[len('--file='):]
tmp_file = arg.removeprefix('--file=')
sys.argv.pop(i)
break
selected_files = sys.argv[1:]

View File

@ -124,7 +124,7 @@ def parse(quteproc):
title_prefix = 'Browse directory: '
# Strip off the title prefix to obtain the path of the folder that
# we're browsing
path = pathlib.Path(soup.title.string[len(title_prefix):])
path = pathlib.Path(soup.title.string.removeprefix(title_prefix))
container = soup('div', id='dirbrowserContainer')[0]

View File

@ -988,7 +988,7 @@ def test_restart(request, quteproc_new):
quteproc_new.wait_for_quit()
assert line.message.startswith(prefix)
pid = int(line.message[len(prefix):])
pid = int(line.message.removeprefix(prefix))
os.kill(pid, signal.SIGTERM)
try:

View File

@ -25,10 +25,10 @@ class Naming:
def camel_to_snake(naming, name):
if naming.prefix:
assert name.startswith(naming.prefix)
name = name[len(naming.prefix):]
name = name.removeprefix(naming.prefix)
if naming.suffix:
assert name.endswith(naming.suffix)
name = name[:-len(naming.suffix)]
name = name.removesuffix(naming.suffix)
# https://stackoverflow.com/a/1176023
return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()

View File

@ -55,7 +55,7 @@ def test_js_quirks(config_stub, js_tester_webengine, base_url, source, expected)
def test_js_quirks_match_files(webengine_tab):
quirks_path = pathlib.Path(qutebrowser.__file__).parent / "javascript" / "quirks"
suffix = ".user.js"
quirks_files = {p.name[:-len(suffix)] for p in quirks_path.glob(f"*{suffix}")}
quirks_files = {p.name.removesuffix(suffix) for p in quirks_path.glob(f"*{suffix}")}
quirks_code = {q.filename for q in webengine_tab._scripts._get_quirks()}
assert quirks_code == quirks_files
@ -66,7 +66,7 @@ def test_js_quirks_match_settings(webengine_tab, configdata_init):
valid_values = opt.typ.get_valid_values()
assert valid_values is not None
quirks_config = {
val[len(prefix):].replace("-", "_")
val.removeprefix(prefix).replace("-", "_")
for val in valid_values
if val.startswith(prefix)
}

View File

@ -57,7 +57,7 @@ def qtest_key(request):
def test_key_data_keys():
"""Make sure all possible keys are in key_data.KEYS."""
key_names = {name[len("Key_"):]
key_names = {name.removeprefix("Key_")
for name in testutils.enum_members(Qt, Qt.Key)}
key_data_names = {key.attribute for key in sorted(key_data.KEYS)}
diff = key_names - key_data_names
@ -66,7 +66,7 @@ def test_key_data_keys():
def test_key_data_modifiers():
"""Make sure all possible modifiers are in key_data.MODIFIERS."""
mod_names = {name[:-len("Modifier")]
mod_names = {name.removesuffix("Modifier")
for name, value in testutils.enum_members(Qt, Qt.KeyboardModifier).items()
if value not in [Qt.KeyboardModifier.NoModifier, Qt.KeyboardModifier.KeyboardModifierMask]}
mod_data_names = {mod.attribute for mod in sorted(key_data.MODIFIERS)}

View File

@ -163,7 +163,7 @@ class TestFileHandling:
msg = message_mock.getmsg(usertypes.MessageLevel.info)
prefix = 'Editor backup at '
assert msg.text.startswith(prefix)
fname = msg.text[len(prefix):]
fname = msg.text.removeprefix(prefix)
with qtbot.wait_signal(editor.editing_finished):
editor._proc._proc.finished.emit(0, QProcess.ExitStatus.NormalExit)