Introduction
Python Data Types & Operators
Conditional Statements
Python Loops
Python Strings
Python Lists
Python Tuple
Operation on Strings
Length of a String:
We can find the length of a string using len() function.
Example:
str1="hello" # set of characters
print(str1)
print(type(str1))
print(len(str1)) # no of characters in a string
Output:
hello
<class 'str'>
5
String as an Array:(indexing and Slicing)
A string is essentially a sequence of characters also called an array. Thus we can access the elements of this array.
Example:
str1="dipanshu"
print(str1)
print(str1[0]) # indexing is used to print a specfic character
print(str1[-1])
print(str1[-8])
Output:
dipanshu
d
u
d
Slicing in string:
To access portion of string elements
Example:
word="Amazing"
print(word) # amazing
print(word[0:7]) # amazing
print(word[0:3]) # ama
print(word[2:5]) # azi
print(word[-7:-3]) # step by default +1 amaz
print(word[-5:-1]) # azin
print(word[:7]) # it will start from 0
print(word[:5])
print(word[3:]) # it will end upto length
print(word[2:6:2])
Output:
Amazing
Amazing
Ama
azi
Amaz
azin
Amazing
Amazi
zing
ai
Loop through a String:
Strings are arrays and arrays are iterable. Thus we can loop through strings.
Example:
alphabets = "ABCDE"
for i in alphabets:
print(i)
Output:
A
B
C
D
E