Accessing characters in Python String
In Python Programming tutorials, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types that will cause a TypeError.
Python String Positive Indexing
In this example, we will define a string in Python Programming and access its characters using positive indexing. The 0th element will be the first character of the string.
String1 = "w3wiki"
print("Initial String: ", String1)
# Printing First character
print("First character of String is: ", String1[0])
Output:
Initial String: w3wiki
First character of String is: G
Python String Negative Indexing
In this example, we will access its characters using negative indexing. The -3th element is the third last character of the string.
String1 = "w3wiki"
print("Initial String: ", String1)
# Printing Last character
print("Last character of String is: ", String1[-3])
Output
Initial String: w3wiki
Last character of String is: e
Python String
A String is a data structure in Python Programming that represents a sequence of characters. It is an immutable data type, meaning that once you have created a string, you cannot change it. Python String are used widely in many different applications, such as storing and manipulating text data, representing names, addresses, and other types of data that can be represented as text.
Table of Content
- What is a String in Python?
- Create a String in Python
- Accessing characters in Python String
- String Slicing
- Python String Reversed
- Deleting/Updating from a String
- Escape Sequencing in Python
- Python String Formatting
- Useful Python String Operations
- Python String constants
- Deprecated string functions
- FAQ’s on Python String