Python | Access and print characters from the string

Here, we are going to learn how to access and print characters from the string in Python? We will print characters by index. By IncludeHelp Last updated : September 16, 2023

Problem statement

Given a string, we have to access characters from the string in Python.

Example

Consider the below example with sample input and output:

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

Python program to access and print characters from the string

# 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

The output of the above program is:

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

Python String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.