A string in Python is a sequence of Unicode characters enclosed by a single quote or double-quotes. Python strings are immutable in nature. Which means we can not update or delete string characters once it’s created.
Creating a String in Python
In Python, a string can be created by simply placing Unicode characters inside single or double quotes or even triple quotes. Unlike other programming languages, single and double quotes are treated as the same in Python.
Note: There is no char data type in Python. A single character is a string of length one in Python.
Example:
# A program to create strings in Python # Creating a string using single quotes str1 = 'Welcome to Programmers Portal' print('A string created using single quotes:') print(str1) # Creating a string using double quotes str2 = "Welcome to Programmers Portal" print('nA string created using double quotes:') print(str2) # Creating a string using triple quotes str3 = '''Hi, I am a mulit-line string''' print('nA string created using triple quotes:') print(str3) # Creating a single character string str4 = 'H' print('nA single character string:') print(str4)
Output:
A string created using single quotes:
Welcome to Programmers Portal
A string created using double quotes:
Welcome to Programmers Portal
A string created using triple quotes:
Hi, I
am a mulit-line
string
A single character string:
H
Accessing String Characters
Characters of a string can be accessed using indexes.
There are two types of indexing in Python.
- Positive indexing
- Negative indexing
We can use both indexing methods to access characters of a string in Python. Let’s discuss each method.
1. Positive Indexing:
In positive indexing, the index starts from 0. This means the first character has an index of 0, the second character has an index of 1, the third character has an index of 2, and so on up to the end of the string. See the image below:
# A program to explain positive indexing in Python strings my_str = 'Programmer' print('First Character of string: ') print('my_str[0]: ', my_str[0]) print('nSecond character of string: ') print('my_str[1]: ', my_str[1]) print('nLast character of string: ') print('my_str[9]: ', my_str[9])
Output:
First Character of string:
my_str[0]: P
Second character of string:
my_str[1]: r
Last character of string:
my_str[9]: r
2. Negative Indexing
In python, it is also possible to use negative indexes to access the characters of a string.
Negative index starts from the end of the string. The last character of the string has an index of -1, the second last has an index of -2, the third last has an index of -3, and so on up to the starting of the string. See the image below:
# A Program to Explain Negative Indexing in Python Strings my_str = 'Programmer' print('Last Character of string: ') print('my_str[-1]: ', my_str[-1]) print('nSecond last character of string: ') print('my_str[-2]: ', my_str[-2]) print('nFirst character of string: ') print('my_str[-10]: ', my_str[-10])
Output:
Last Character of string:
my_str[-1]: r
Second last character of string:
my_str[-2]: e
First character of string:
my_str[-10]: P
Length of a Python String
The length of a string is the same as the number of characters in it. The length of a string can be calculated using the inbuilt function len(). It takes any sequence(here string) as an input parameter and returns the length of it.
# A program to calculate the length of a string in Python empty_str = '' print('Length of empty string: ', len(empty_str)) my_str = 'Programmers Portal' print('nLength of my_str: ', len(my_str))
Output:
Length of empty string: 0
Length of my_str: 18
String Slicing in Python
Slicing a string simply means extracting a substring from a given string. Slicing can be applied to Python lists, tuples, string, etc. Slicing is done with the help of the slicing operator colon ( : ). To slice a string you have to pass a starting index and an end index. The end index is not included in the slicing.
# A program to explain slicing in a Python string my_str = 'Programmers Portal' # Slice the string from 4th character to last print('my_str[1:] = ', my_str[3: ]) # Slice the string from starting to 2nd last index print('nmy_str[:17] = ', my_str[ :17]) # Slice Portal from my_str print('nmy_str[12:17] = ',my_str[12:18]) # Extract the whole string print('nmy_str[:] = ',my_str[:]) # Try slicing using negative indexes yourself
Output:
my_str[1:] = grammers Portal
my_str[:17] = Programmers Porta
my_str[12:17] = Portal
my_str[:] = Programmers Portal
Delete and Update Operations in a Python String
As we already know that Python strings are immutable in nature. Therefore, we can neither update nor delete string characters. However, it is possible to delete the whole string. The whole string can be deleted using the del keyword in Python. In a similar way, it is also possible to replace the existing string with a new one. See the example below:
# A program to explain string delete and update in Python my_str = 'Hello' print('Original String: ', my_str) # Replacing with a new one my_str = 'Hello updated' print('nUpdated String: ', my_str) # Deleting the whole string del my_str # It will throw an error print('nAfter deleting whole string: ', my_str)
Output:
Original String: Hello
Updated String: Hello updated
Traceback (most recent call last):
File "jdoodle.py", line 14, in <module>
print('nAfter deleting whole string: ', my_str)
NameError: name 'my_str' is not defined
String Concatenation
In Python, it is possible to concatenate/combine two or more strings and form a new string.
There are two methods to concatenate two or more strings:
- Using addition operator( + )
- Using multiplication operator( * )
1. String Concatenation Using addition operator( + )
The addition operator + can be used to add two or more strings at a time. See the example below:
# A program to explain concatenation in Python Strings str1 = 'Programmers' str2 = 'Portal' # Adding two strings str3 = str1 + str2 print('str1 = ', str1) print('str2 = ', str2) print('str1 + str2 = ', str3)
Output:
str1 = Programmers
str2 = Portal
str1 + str2 = ProgrammersPortal
2. String Concatenation Using multiplication operator (*)
The multiplication operator( * ) is used to repeat a string one or more time. It can not be used to concatenate different strings like the addition operator does. See the example below:
# A program to explain concatenation using * operator in Python Strings my_str = 'Hello' # Repeat only once print('my_str*1 = ', my_str*1) # Repeat two times print('nmy_str*2 = ', my_str*2) # Repeat three times print('nmy_str*3 = ', my_str*3)
Output:
my_str*1 = Hello
my_str*2 = HelloHello
my_str*3 = HelloHelloHello
String Membership
We can use membership operators to check if a given string is present in another string or not. Python provides us two membership operators to check membership.
- in operator
- not in operator
The in operator returns True if the sub-string exists in the main string otherwise, it returns False.
The not in operator works exactly opposite to the in operator.
See the example below:
# A program to explain membership in Python Strings main_str = 'Hi, Welcome to Programmers Portal' test_str = 'to' # Using the in operator print('test_str in main_str = ', test_str in main_str) # Using the not in operator print('ntest_str not in main_str = ', test_str not in main_str)
Output:
test_str in main_str = True
test_str not in main_str = False