In this tutorial, we will discuss Python String and also learn how to create and modify a string in python.
Python String
A python string is an immutable collection or a sequence of characters, and these characters could be symbols, Alphabets, and digits too. The Computer does not understand the characters and symbols it only understands binary values in the form of 0 and 1.
How to create a String
All the characters are written inside single quotes or double quotes known as a string. If you use triple quotes to represent a string it will become a multi-line docstring.
Let’s understand it with an example:
#Output
Access characters from a string:
Like a list, each string character store in a sequence and using indexing we can retrieve any random character from a string. If a string contains 25 characters then the range of its indexing would be from 0 to 24 and if we try to access an index value more than 24 it will throw an index error . Like a list, negative indexing can be also applied on a string where -1 index represents the last character of the string.
Let’s understand it with an example:
#Output
What if we use an index value out of range?
#Output
Change or delete a string value:
Strings are immutable which mean we cannot alter its character once it assigned. Though we can assign a new string to the same variable name, it does not mean we change the string it means that we have just changed the reference value to another string.
Let’s understand it with an example:
To delete a string object we use del keyword.
Example
#Output
String Operations:
There are many operations that can be performed on a string.
1. String Concatenation
String concatenation means joining two string to form a single one. We use + operator between two strings to concatenate them. Let’s understand it with an example:
#Output
use of * operator with a string
we can use * operator on a string but it should be operated between a string and an integer it will create multiple values of the string and concatenate them. Let’s understand it with an example:
#Output
2. Iterating through a String
A string can be used as an iterator and using a for loop we can iterate through each character of a string. Let’s understand it with an example:
#Output
3. Membership tests of string
In the membership test, we use in a keyword to check whether the specific character present in a given string or not and return a Boolean value (True or False).
Built-in functions:
len(): len() function returns the total number of character present in the string example:
String Methods
lower() = it convert each string character to lowercase upper() = it convert each string character to uppercase join() = it is used to join all items of a list and make a single string of it split()=converts a string to a list. find() = it return the index value of the character replace() = it replace one character with another.
Let’s understand it with an example: