Page Contents
String in Python is a collection of one or more characters . It can be surrounded by single quote , double quote , triple single quote or triple double quote . To create a multiline string we use triple single quote or triple double quote .
How to create a String in Python ?
There are multiple ways to create a string in Python –
- Using single quote (
''
) - Using double quote (
""
) - Using triple single quote (
''' '''
) - Using triple double quote (
""" """
) - Using
str()
function
To check if it is a string or not we can use type()
function .
Example 1:
# Creating a string in Python
# Using single quote ('')
single_quoted_string = 'coding conception'
# checking the type
print("type of single_quoted_string",type(single_quoted_string))
# using double quote ("")
double_quoted_string = "coding conception"
# checking the type
print("type of double_quoted_string",type(double_quoted_string))
# using triple single quote ('''''')
triple_single_string = '''coding conception'''
# checking the type
print("type of triple_single_string",type(triple_single_string))
# using triple double quote ("""""")
triple_double_string = """coding conception"""
# checking the type
print("type of triple_double_string",type(triple_double_string))
# using str function
str_string = str(10)
# checking the type
print("type of str_string",type(str_string))
type of single_quoted_string <class 'str'> type of double_quoted_string <class 'str'> type of triple_single_string <class 'str'> type of triple_double_string <class 'str'> type of str_string <class 'str'>
In the above code we have seen how we can create a string using different way .
Note :
We use triple single quote or triple double quote only to create a multiline string otherwise we use single quote , double quote or str()
function .
Example :
# multiline string
mul_string = '''I am Rajkumar Bhattacharya
author at Codingconception.com'''
print(mul_string)
I am Rajkumar Bhattacharya author at Codingconception.com
How to access characters in a String in Python ?
We can access characters from a string using its index . So first we need to know about how indexing works in Python . For this reason we need to see the below image –
From the above image we can see that in Python index starts from 0
. So , index of first "C"
from
“Coding Conception” is 0
, index of first "o"
from "Coding Conception"
is 1
and so on . We can also see that length of "Coding Conception"
is 17
but the last index number is 16
.
There is also one concept in Python that is negative indexing . Negative indexing in Python starts from -1
which points to the last element . We can see from the above image that -1
index points to the last character "n"
of "Coding Conception"
, -2
index points to the 2nd last character "o"
of "Coding Conception"
.
Example 1:
myString = "Coding Conception"
# Accessing first element
print("myString[0] =",myString[0])
# Accessing second element
print("myString[1] =",myString[1])
# Accessing last element
print("myString[len(myString)-1] =",myString[len(myString)-1])
myString[0] = C myString[1] = o myString[len(myString)-1] = n
- In the above code first we have declared a string
myString
as"Coding Conception"
- Then we have printed first character of the string by
myString[0]
that isC
- After that we have printed second character of the string by
myString[1]
that iso
- Then we have printed last character of the string by
myString[len(myString)-1]
that isn
. As length of string is17
somyString[len(myString)-1]
treated asmyString[16]
.
Example 2:
myString = "Coding Conception"
# Accessing last element
print("myString[-1] =",myString[-1])
# Accessing second last element
print("myString[-2] =",myString[-2])
# Accessing first element
print("myString[-len(myString)] =",myString[-len(myString)])
myString[-1] = n myString[-2] = o myString[-len(myString)] = C
- In the above code first we have declared a string
myString
as"Coding Conception"
- Then we have printed last character of the string by
myString[-1]
that isn
- After that we have printed second last character of the string by
myString[-2]
that iso
- Then we have printed first character of the string by
myString[-len(myString)]
that isC
. As length of string is17
somyString[-len(myString]
treated asmyString[-17]
.
Note :
If we give index outside the range then it will give IndexError
.
myString = "Coding Conception"
print(myString[17])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_9420/3574012407.py in <module> 1 myString = "Coding Conception" ----> 2 print(myString[17]) IndexError: string index out of range
In the above code as the length of the string is 17
so index of last character will be (17-1)=16
. For this reason when we have given index as 17
Python has raised an IndexError
.
Now , we have understood about indexing in Python . Now we will discuss about slicing of string in Python –
Slicing of String in Python
We can slice one or more character from a string using its index .
Syntax of Slicing
object[start : stop : step]
Parameters of Slicing
- start = Optional , start specifies index number from where slicing will start . Default value is
0
. - Stop = Optional , stop specifies index number at where slicing will end but this number is excluded . Default value is
(length of the object)
. - step = Optional , An integer number which specifies the incrementation . Default is
1
Return type of Slicing
It returns a copy of the given datatype .
Example 1:
myString = "Coding Conception"
# if nothing is given
# it will print the full string
print("myString[::] =",myString[::])
# slicing 2nd character to 4th character
print("myString[1:4] =",myString[1:4])
# as index of 4th character is 3 and stop
# parameter is excluded so we need to give
# stop parameter as 3+1=4
# if start parameter is not given
# then python will take it as 0
print("myString[:4] =",myString[:4])
# if stop parameter is not given
# then python will take it as len(myString)-1
print("myString[5:] =",myString[5:])
# if we want to print 1st ,3rd and 5th character
# then we need to give step parameter as 2
print("myString[0:5:2] =",myString[0:5:2])
# by default python takes step parameter as 1
myString[::] = Coding Conception myString[1:4] = odi myString[:4] = Codi myString[5:] = g Conception myString[0:5:2] = Cdn
In the above code we have seen various examples about slicing of string in Python
Example 2:
myString = "Coding Conception"
# slicing using negative indexing
# slicing 2nd last character to 4th last character
print("myString[-2:-5:-1] =",myString[-2:-5:-1])
# as index of 4th last character is -4 and stop
# parameter is excluded so we need to give
# stop parameter as -(4+1)=-5
# but to go -2 to -5 we need to give step as -1
# if we want to print last ,3rd last and 5th last character
# then we need to give step parameter as 2
print("myString[-1:-6:-2] =",myString[-1:-6:-2])
myString[-2:-5:-1] = oit myString[-1:-6:-2] = nip
Note :
When we use negative step parameter then default value of start and stop parameter becomes -1
and -(length of the object)
.
Example :
myString = "Coding Conception"
# when start and stop parameter both is not given
# python takes start and stop as -1 and -17
print("myString[::-1] =",myString[::-1])
# in this example we just reverse the string
# when stop parameter is not given python takes stop as -17
print("myString[5::-1] =",myString[5::-1])
# when start parameter is not given python takes start as -1
print("myString[:8:-1] =",myString[:8:-1])
myString[::-1] = noitpecnoC gnidoC myString[5::-1] = gnidoC myString[:8:-1] = noitpecn
How to update or delete a string in Python ?
In Python strings are immutable which means unchangeable . So , we can not change or update a string in Python . If we want to change a string using its index then it will raise a TypeError
Example 1:
myString = "Coding Conception"
# we want to change 2nd character "o" with "p"
myString[1]="p"
TypeError Traceback (most recent call last) C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_5676/3264364102.py in <module> 2 3 # we want to change 2nd character "o" with "p" ----> 4 myString[1]="p" TypeError: 'str' object does not support item assignment
In the above code as we want to change myString
using its index , it gave us a TypeError
.
Example 2:
However , we can redeclare the same variable with other string . In that case program will not give any error –
myString = "Coding Conception"
# printing the string
print("myString =",myString)
# redeclaring the same variable with other string
myString="Rajkumar"
# printing the nrw string
print("myString =",myString)
myString = Coding Conception myString = Rajkumar
In the above code by redeclaring the same variable we successfully change the string .
Example 3:
To delete a string we can use del
keyword . But if we want to access the string after deleting it using del
keyword it will raise a NameError
.
myString = "Coding Conception"
# printing the string
print("myString =",myString)
# deleting the string
del myString
# printing the deleted string
# it will give error
print("myString =",myString)
myString = Coding Conception
--------------------------------------------------------------------------- NameError Traceback (most recent call last) C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_5676/1461000573.py in <module> 8 9 # printing the deleted string ---> 10 print("myString =",myString) NameError: name 'myString' is not defined
In the above code after declaring the string we have printed the string successfully . But after deleting the string when we want to print the string it has raised a NameError
.
Iterating a String in Python
We can iterate a string in Python using for-loop
and while-loop
.
Example 1:
# for loop with string as iterator
myString = "Rajkumar"
for letter in myString:
print(letter)
R a j k u m a r
In the above code we have iterated all character from myString
using for-loop
.
Example 2:
# python while loop with string datatype
name ="rajkumar"
number=0
while number < len(name):
print(name[number])
number+=1
r a j k u m a r
In the above code we have iterated all character from myString
using while-loop
Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .