Python Access and print characters from the string

Here, we will figure out how to access and print characters from the string in Python? We will print characters by file.

Given a string, we need to get to characters from the string in Python.

Example:

    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...

Program:

# 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

Output:

    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

Leave a Comment

error: Alert: Content is protected!!