Uma str é uma sequência imutável de pontos de código Unicode.
Isso pode incluir letras, sinais diacríticos, caracteres de posicionamento, números, símbolos de moeda, emoji, pontuação, espaço e quebras de linha, entre outras coisas.
As strings implementam todas as operações comuns de sequência e podem ser percorridas com a sintaxe for item in <str> ou for index, item in enumerate(<str>).
Pontos de código individuais (strings de comprimento 1) podem ser referenciados por um número de índice 0-based index a partir da esquerda, ou por um índice -1-based index a partir da direita.
Strings podem ser concatenadas com <str> + <other str> ou <str>.join(<iterable>) e divididas com <str>.split(<separator>).
Elas também oferecem várias outras opções de formatação e montagem.
Para trabalhar ainda mais com strings, o Python oferece um rico conjunto de métodos de string para pesquisar, limpar, transformar, traduzir e muitas outras operações.
Alguns dos métodos de str mais usados incluem:
<str>.startswith(<substr>) e <str>.endswith(<substr>)
<str>.title(), <str>.upper()/<str>.lower() e <str>.swapcase()
<str>.strip(<chars>), <str>.lstrip(<chars>) ou <str>.rstrip(<chars>)
<str>.replace(<old>, <new>)
Sendo imutável, o valor de um objeto str na memória não pode mudar; métodos que parecem modificar uma string retornam uma nova cópia ou instância desse objeto str.
<str>.endswith(<suffix>) retorna 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 "caractere" de cada "palavra" encontrada.
No Python, isso depende muito do codec de idioma usado e de como aquele idioma representa palavras e caracteres.
Também pode haver regras de locale em vigor para um idioma ou conjunto de caracteres.
>>> 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>) retorna uma cópia da str com os <chars> iniciais e finais removidos.
Os pontos de código especificados em <chars> não são um prefixo nem um sufixo: todas as combinações desses pontos de código serão removidas, a partir das duas extremidades da string.
Se nada for especificado em <chars>, todas as combinações de pontos de código de espaço em branco serão removidas.
Se você quiser remover só do lado esquerdo ou só do lado direito, pode usar <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>) retorna 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 facilitam muito remover prefixos e sufixos.
<str>.removeprefix(<substring>) retorna a string sem o prefixo (string[len(<substring>):]). Se o <substring> não estiver presente, uma cópia da string original será retornada.
# removing a prefix
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'bookkeeper'.removeprefix('book')
'keeper'
<str>.removesuffix(<substring>) retorna a string sem o sufixo (string[:-len(substring)]). Se o <substring> não estiver presente, uma cópia da string original será retornada.
# 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 How to Unicode na documentação do Python traz muitos detalhes sobre Unicode, codificação, bytes e outras questões técnicas de se trabalhar com strings no Python.
O Python também dá suporte a expressões regulares por meio do módulo re, que será abordado em um conceito futuro.