Wednesday, February 12, 2020

Accessing Characters in Python String

Python String is an ordered sequence of characters and stored as an array. In order to access characters in a String you need to specify string name followed by index in the square brackets. Note that index is 0 based and valid range for string of length n is 0..(n-1).

In String in Python you can also use negative indexing. When negative number is used as index String is accessed backward so -1 refers to the last character, -2 second last and so on.

Accessing characters from String in Python

Getting characters from a string in Python example

s = "Hello World"
#first character
print(s[0])
#3rd character
print(s[2])
print('length of String', len(s))
#last character
print(s[len(s)-1])

Output

H
l
length of String 11
d

Getting characters using negative indexing

s = "Hello World"
# last character
print(s[-1])
print('length of String', len(s))
# first character by making the index negative
print(s[-(len(s))])

Output

d
length of String 11
H

That's all for this topic Accessing Characters in Python String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Removing Spaces From String in Python
  2. Check String Empty or Not in Python
  3. String Length in Python - len() Function
  4. Python while Loop With Examples
  5. Multiple Inheritance in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Python Program to Find Factorial of a Number
  3. Python Functions : Returning Multiple Values
  4. Tuple in Python With Examples
  5. BigDecimal in Java
  6. Java ThreadLocal Class With Examples
  7. Difference Between Two Dates in Java
  8. Transaction Management in Spring