Un str es una secuencia inmutable de puntos de código Unicode.
Puede incluir letras, signos diacríticos, caracteres de posicionamiento, números, símbolos de moneda, emoji, puntuación, espacios y saltos de línea, entre otras cosas.
Los string implementan todas las operaciones comunes de secuencia y se pueden recorrer con la sintaxis for item in <str> o for index, item in enumerate(<str>).
Se puede hacer referencia a puntos de código individuales (strings de longitud 1) mediante un número de 0-based index desde la izquierda, o un número de -1-based index desde la derecha.
Los string se pueden concatenar con <str> + <other str> o <str>.join(<iterable>) y dividir con <str>.split(<separator>).
También ofrecen muchas otras opciones de formato y composición.
Para trabajar más a fondo con los string, Python ofrece un amplio conjunto de métodos de string para buscar, limpiar, transformar, traducir y muchas otras operaciones.
Algunos de los métodos de str más usados son:
<str>.startswith(<substr>) y <str>.endswith(<substr>)
<str>.title(), <str>.upper()/<str>.lower() y <str>.swapcase()
<str>.strip(<chars>), <str>.lstrip(<chars>) o <str>.rstrip(<chars>)
<str>.replace(<old>, <new>)
Como es inmutable, el valor de un objeto str en memoria no puede cambiar; los métodos que parecen modificar un string devuelven una copia nueva o una instancia nueva de ese objeto str.
<str>.endswith(<suffix>) devuelve True si el string termina con <suffix> y False en caso contrario.
>>> '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() analiza un string y pone en mayúscula el primer «carácter» de cada «palabra» que encuentra.
En Python, esto depende mucho del códec de idioma que se use y de cómo ese idioma en particular representa palabras y caracteres.
También puede haber reglas de configuración regional para un idioma o un 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>) devuelve una copia del str con los <chars> del principio y del final eliminados.
Los puntos de código especificados en <chars> no son un prefijo ni un sufijo: se eliminarán todas las combinaciones de esos puntos de código empezando por ambos extremos del string.
Si no se especifica nada para <chars>, se eliminarán todas las combinaciones de puntos de código de espacio en blanco.
Si solo quieres quitar caracteres de la izquierda o de la derecha, puedes usar <str>.lstrip(<chars>) y <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>) devuelve una copia del string con todas las apariciones de <substring> reemplazadas por <replacement substring>.
La cita que aparece abajo es 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'
🌟Nuevo en Python 3.9
Python 3.9 incorpora dos nuevos métodos de string que facilitan mucho quitar prefijos y sufijos.
<str>.removeprefix(<substring>) devuelve el string sin el prefijo (string[len(<substring>):]). Si <substring> no está presente, se devuelve una copia del string original.
# removing a prefix
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'bookkeeper'.removeprefix('book')
'keeper'
<str>.removesuffix(<substring>) devuelve el string sin el sufijo (string[:-len(substring)]). Si <substring> no está presente, se devuelve una copia del string original.
# removing a suffix
>>> 'TestHook'.removesuffix('Hook')
'Test'
>>> 'bookkeeper'.removesuffix('keeper')
'book'
Para ver más ejemplos y métodos, el tutorial informal es un buen punto de partida. How to Unicode en la documentación de Python ofrece un gran nivel de detalle sobre Unicode, la codificación, los bytes y otras consideraciones técnicas para trabajar con string en Python.
Python también admite expresiones regulares a través del módulo re, que se tratará en un concepto futuro.