Python | Acceder e imprimir caracteres de la cadena

Aquí, vamos a aprender cómo acceso e imprimir caracteres de la cadena en Python ? Vamos a imprimir caracteres de índice.

Dada una cadena, tenemos que acceder a los caracteres de la cadena en Python.

Ejemplo:

    Input:
str: "Hello world"
Output:
First character: H
Second character: e
Last character: d
Second last character: l
Characters from 0th to 4th index: Hello
And, so on...

Programa:

# access characters in string
# declare, assign string
str = "Hello world"
# print complete string
print "str:", str
# print first character
print "str[0]:", str[0]
# print second character
print "str[1]:", str[1]
# print last character
print "str[-1]:", str[-1]
# print second last character
print "str[-2]:", str[-2]
# print characters from 0th to 4th index i.e.
# first 5 characters
print "str[0:5]:", str[0:5]
# print characters from 2nd index to 2nd last index
print "str[2,-2]:", str[2:-2]
# print string character by character
print "str:"
for i in str:
print i,
#comma after the variable
# it does not print new line

salida

    str: Hello world
str[0]: H
str[1]: e
str[-1]: d
str[-2]: l
str[0:5]: Hello
str[2,-2]: llo wor
str:
H e l l o w o r l d


Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *