Q:

Python | Access and print characters from the string

belongs to collection: Python String Programs

0

Given a string, we have to access 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...

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Declare, assign and print the string (Dif... >>