Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to get the character(s) in a string in Python

Onyejiaku Theophilus Chidalu

Overview

The index of a character is its position in the string. Python strings are indexed starting from zero to the length of the given string - 1. For example, the string Python is indexed as 0,1,2,3,4,5. The 0 is the index or position of the first character, P, in the string Python, and 1, 2, 3, 4, and 5 are the indexes or positions of y, t, h, o, and n, respectively. Below are some ways to get the character(s) from a string by providing the index(es).

Code

# introducing a string
Name = 'Python Course'
# To get the 1st character of the given string
print(Name[0])
# To get the 2nd character of the given string  
print(Name[1])
# To get 7th character of the given string
print(Name[6])

You can use a negative index starting from the end of a string to get the character of a string, as shown below.

Name = 'Python Course'
# To get the last character of the string 
print(Name[-1])
# To get the 2nd last character 
print(Name[-2])

In the example below, you can use the same syntax to extract a few characters instead of just one.

Name = 'Python Course'
# To get the first three characters
print(Name[0:3])
# To get all the characters startimng from zero index
print(Name[0:]) 
# To get all the characters starting from zero to the 5th index
print(Name[:6])
# To also get all the characters of the string
print(Name[:])

When you use the syntax print(Name[0:]), Python will assume the indexes from zero to the last index by default. The same applies to print(Name[:6]) and print(name[:]); Python will assume the indexes from zero to the 5th index and from zero to the last index, respectively.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring