Percursos
/
Python
Python
/
Programa
/
Métodos de string
Mé

Métodos de string em Python

60 exercícios

Sobre Métodos de string

Uma str é uma sequência imutável de pontos de código Unicode. Pode incluir letras, sinais diacríticos, carateres de posicionamento, números, símbolos de moeda, emoji, pontuação, espaços e quebras de linha, entre outros.

As strings implementam todas as operações de sequência comuns e podem ser percorridas com a sintaxe for item in <str> ou for index, item in enumerate(<str>). Cada ponto de código individual (strings de comprimento 1) pode ser referenciado por um número de 0-based index a partir da esquerda, ou por um número de -1-based index a partir da direita.

As strings podem ser concatenadas com <str> + <other str> ou <str>.join(<iterable>) e divididas com <str>.split(<separator>). Oferecem também muitas outras opções de formatação e de composição.

Para trabalhar mais a fundo com strings, o Python oferece um conjunto rico de métodos de string para pesquisar, limpar, transformar, traduzir e muitas outras operações.

Alguns dos métodos str mais usados incluem:

  • Verificar prefixos/sufixos com <str>.startswith(<substr>) e <str>.endswith(<substr>)
  • Alterar as maiúsculas e minúsculas de uma string com métodos como <str>.title(), <str>.upper()/<str>.lower() e <str>.swapcase()
  • Remover carateres no início ou no fim de uma string com <str>.strip(<chars>), <str>.lstrip(<chars>) ou <str>.rstrip(<chars>)
  • Substituir substrings com o método <str>.replace(<old>, <new>)

Sendo imutável, o valor de um objeto str na memória não pode mudar; os métodos que parecem modificar uma string devolvem uma nova cópia ou instância desse objeto str.

<str>.endswith(<suffix>) devolve True se a string terminar com <suffix> e False caso contrário.

>>> 'My heart breaks. 💔'.endswith('💔')
True

>>> 'cheerfulness'.endswith('ness')
True

# Punctuation is part of the string, so needs to be included in any endswith match.
>>> 'Do you want to 💃?'.endswith('💃')
False

>>> 'The quick brown fox jumped over the lazy dog.'.endswith('dog')
False

<str>.title() analisa uma string e coloca em maiúscula o primeiro "caráter" de cada "palavra" que encontra. Em Python, isto depende muito do codec da linguagem usado e da forma como essa linguagem representa palavras e carateres. Também pode haver regras de locale associadas a uma linguagem ou a um conjunto de carateres.

>>> man_in_hat_th = 'ผู้ชายใส่หมวก'
>>> man_in_hat_ru = 'мужчина в шляпе'
>>> man_in_hat_ko = '모자를 쓴 남자'
>>> man_in_hat_en = 'the man in the hat.'

>>> man_in_hat_th.title()
'ผู้ชายใส่หมวก'

>>> man_in_hat_ru.title()
'Мужчина В Шляпе'

>>> man_in_hat_ko.title()
'모자를 쓴 남자'

>> man_in_hat_en.title()
'The Man In The Hat.'

<str>.strip(<chars>) devolve uma cópia da str sem os <chars> do início e do fim. Os pontos de código indicados em <chars> não são um prefixo nem um sufixo: são removidas todas as combinações dos pontos de código, a partir de ambas as extremidades da string. Se não se indicar nada em <chars>, são removidas todas as combinações de pontos de código de espaço em branco. Se só se quiser remover do lado esquerdo ou do lado direito, pode usar-se <str>.lstrip(<chars>) e <str>.rstrip(<chars>).

# This will remove "https://", because it can be formed from "/stph:". 
>>> 'https://unicode.org/emoji/'.strip('/stph:')
'unicode.org/emoji'

# Removal of all whitespace from both ends of the str.
>>> '   🐪🐪🐪🌟🐪🐪🐪   '.strip()
'🐪🐪🐪🌟🐪🐪🐪'

>>> justification = 'оправдание'
>>> justification.strip('еина')
'оправд'

# Prefix and suffix in one step.
>>> 'unaddressed'.strip('dnue')
'address'

>>> '  unaddressed  '.strip('dnue ')
'address'

<str>.replace(<substring>, <replacement substring>) devolve uma cópia da string com todas as ocorrências de <substring> substituídas por <replacement substring>.

A citação usada abaixo é de The Hunting of the Snark, de Lewis Carroll

# The Hunting of the Snark, by Lewis Carroll
>>> quote = '''
"Just the place for a Snark!" the Bellman cried,
   As he landed his crew with care;
Supporting each man on the top of the tide
   By a finger entwined in his hair.

"Just the place for a Snark! I have said it twice:
   That alone should encourage the crew.
Just the place for a Snark! I have said it thrice:
   What I tell you three times is true."
'''

>>> quote.replace('Snark', '🐲')
...
'\n"Just the place for a 🐲!" the Bellman cried,\n   As he landed his crew with care;\nSupporting each man on the top of the tide\n   By a finger entwined in his hair.\n\n"Just the place for a 🐲! I have said it twice:\n   That alone should encourage the crew.\nJust the place for a 🐲! I have said it thrice:\n   What I tell you three times is true."\n'

>>> 'bookkeeper'.replace('kk', 'k k')
'book keeper'

🌟Adicionado recentemente no Python 3.9

O Python 3.9 introduz dois novos métodos de string que tornam muito mais fácil remover prefixos e sufixos.

<str>.removeprefix(<substring>) devolve a string sem o prefixo (string[len(<substring>):]). Se o <substring> não estiver presente, é devolvida uma cópia da string original.

# removing a prefix
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'bookkeeper'.removeprefix('book')
'keeper'

<str>.removesuffix(<substring>) devolve a string sem o sufixo (string[:-len(substring)]). Se o <substring> não estiver presente, é devolvida uma cópia da string original.

# removing a suffix
>>> 'TestHook'.removesuffix('Hook')
'Test'
>>> 'bookkeeper'.removesuffix('keeper')
'book'

Para mais exemplos e métodos, o tutorial informal é um bom ponto de partida. O Como usar Unicode na documentação do Python oferece muito detalhe sobre Unicode, codificação, bytes e outras considerações técnicas para trabalhar com strings em Python.

O Python também suporta expressões regulares através do módulo re, que será abordado num conceito futuro.

Editar via GitHub A ligação abre numa nova janela ou separador

Aprende Métodos de string

A prática está bloqueada

Desbloqueia mais 3 exercícios para praticares Métodos de string