Programador Leigo
⚡ 60 segundos strings

Remover prefixo e sufixo de strings (Python 3.9+)

removeprefix() e removesuffix() são mais seguros que replace() para tirar partes fixas do início ou fim de strings.

removeprefix.py
arquivo = 'test_usuario.py'

# Remover prefixo
sem_test = arquivo.removeprefix('test_')
print(sem_test)  # usuario.py

# Remover sufixo
sem_ext = arquivo.removesuffix('.py')
print(sem_ext)  # test_usuario

# Se nao tem o prefixo, retorna a string original
print('hello'.removeprefix('xyz'))  # hello

Compartilhar