Strings, una gran cadena

--Originally published at Mike's Blog

Como ya hemos visto los strings son cualquier valor de texto asignado a una variable. Este valor es inmutable, y como su nombre lo dice, es una cadena de caracteres. Estos valores se pueden escribir de diferentes maneras, siendo la más famosa las comillas (” “). Lo que sea que se encuentre entre las comillas, será un string.

t3_1wrjjx

Los strings sirven para almacenar cualquier caracter, ya se para imprimirlo, o solo guardarlo. Algo que hay que tener en cuenta cuando usamos strings, es que son operables, pero no al grado de los números. Si se tiene un valor numerico guardado como string, no lo vamos a poder operar o comparar. También cabe mencionar que si tenemos un número integer o float, necesitamos convertirlo a string para poderlo imprimir.  El comando para convertir a string es str().

Cuando se tiene un string este no se puede modificar, pero si se puede reemplazar.

Los strings se pueden operar de la siguiente manera:

Operator Description Example
+ Concatenation – Adds values on either side of the operator a + b will give HelloPython
* Repetition – Creates new strings, concatenating multiple copies of the same string a*2 will give -HelloHello
[] Slice – Gives the character from the given index a[1] will give e
[ : ] Range Slice – Gives the characters from the given range a[1:4] will give ell
in Membership – Returns true if a character exists in the given string H in a will give 1
not in Membership – Returns true if a character does not exist in the given string M not in a will give 1
r/R Raw String – Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw
fig4-1
operator, the letter “r,” which precedes the quotation marks. The “r” can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.
print r’\n’ prints \n and print R’\n’prints \n
% Format – Performs String formatting See at next section

Tabla obtenida de: https://www.tutorialspoint.com/python3/python_strings.htm

Una cosa muy importante en Python, es que este es sensible a la capitalización, lo que significa que si compramos dos strings, y varían en la capitalización, no serán los mismos. Por esto siempre hay que cerciorarnos de que las letras coincidan en la totalidad.

Para esto python es capaz de manipular los strings, por ejemplo para poner en minúsculas se utiliza el comando variable.lower(), y para hacerlas mayusculas variable.upper().

fig4-1

Para ver todas las manipulaciones pueden entrar a:

https://www.tutorialspoint.com/python3/python_strings.htm

https://docs.python.org/3/library/string.html