String: Python

MOHIT MEHLAWAT
3 min readJul 8, 2021

--

A string is a sequence of characters arranged in specific order. Python does not have a character data type, a single character is simply a string with a length of 1. In computer, a string is stored and manipulated as a combination of 0′s and 1′s. To represent character data, a translation scheme is used which maps each character to its representative number. The conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular encodings used. In Python, a string is a sequence of Unicode characters.

Accessing Values in String

In Python, individual characters of a String can be accessed by using the method of Indexing. String indexing is zero-based: the first character in the string has index 0, the next is 1, and so on. 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 will cause a TypeError.

In Python, we use brackets [] after an object to call its index.

To access a range of characters in the string, method of slicing is used. Slicing in a string is done by using a slicing operator (colon).

Strings are Immutable

Strings are immutable, that is, once a string is created, the elements within it cannot be changed or replaced. The elements of a string cannot be changed once it has been assigned. Only new strings can be reassigned to the same name.

Print Formatting

The format() method is the most flexible and useful method in formatting strings. The curly braces { } are used as the placeholder in the string and replaced by the format() method argument.

Built-in String Methods

Objects in Python usually have built-in methods. These methods are functions inside the object that can perform actions or commands on the object itself. The methods are called with a period and then the method name. Methods are in the form: object.method(parameters).

There are many more methods which can be found at this link.

--

--