Saturday, January 15, 2022

How to process Strings and their elements in Python Program

Processing Strings and their elements in Python Program
String represents the group of characters. The strings can be declared with use of the single or double quotes.
str1 = 'Welcome to Python Program'
str1 = "Welcome to Python Program"

We can process the strings and their elements using various string functions and methods in Python.
# Finding the Length of a String :
str1 = 'Welcome to Python Program'
n = len(str1)
print(str1)
print('\nThe length of the String is: ', n)

# Output:
The length of the String is:  25

# ------------------------------------------------------------------------------------------------------------------------ #

# Slicing and accessing the elements of a String:
str1 = 'Welcome to Python Program'
n1 = len(str1)

s1 = str1[::]
print('\nAll elements in string are:\n', s1)

s1 = str1[0:n1:1]
print('All elements with step 1 in string are:\n', s1)

s1 = str1[0:n1:2]
print('All elements with step 2 in string are:\n', s1)

s1 = str1[::2]
print('All elements with step 2 in string are:\n', s1)

s1 = str1[3::]
print('The elements from 3rd to end in a string are:\n', s1)

s1 = str1[:4:]
print('The elements from 0 to 3rd in a string are:\n', s1)

# Output:
All elements in string are:
 Welcome to Python Program

All elements with step 1 in string are:
 Welcome to Python Program

All elements with step 2 in string are:
 Wloet yhnPorm
All elements with step 2 in string are:
 Wloet yhnPorm

The elements from 3rd to end in a string are:
 come to Python Program

The elements from 0 to 3rd in a string are:
 Welc

# Reverse Slicing and accessing the elements of a String:
str1 = 'Welcome to Python Program'
s1 = str1[-7:-3]
print('\nThe elements from -3 to -7 (from right) from a string are:\n', s1)

s1 = str1[-7::]
print('The elements from -7 to till end(from right) in a string are:\n', s1)

s1 = str1[-1:-8:-1]
print('The elements from -1 to -8 (in reverse order) in a string are:\n', s1)

s1 = str1[-1::-1]
print('All the elements(in reverse order) from a string are:\n', s1)

# Output:
The elements from -3 to -7 (from right) from a string are:
 Prog

The elements from -7 to till end(from right) in a string are:
 Program

The elements from -1 to -8 (in reverse order) in a string are:
 margorP

All the elements(in reverse order) from a string are:
 margorP nohtyP ot emocleW

# ------------------------------------------------------------------------------------------------------------------------ #

# Accessing each element of a String with For Loop:
print('The elements in a string are:\n')
for i in str1[::]:
    print(i, end=' ')

print('\nThe elements in a string in reverse order are:\n')
for i in str1[:: -1]:
    print(i, end=' ')

# Output:
The elements in a string are:
W e l c o m e   t o   P y t h o n   P r o g r a m 

The elements in a string in reverse order are:
m a r g o r P   n o h t y P   o t   e m o c l e W 

# Accessing each element of a String with While Loop:
print('\nThe elements in a string are:\n')
i = 0
while i < n:
    print(str1[i], end=' ')
    i = i+1

print('\nThe reverse order of elements in a string are:\n')
i = -1
while i >= -n:
    print(str1[i], end=' ')
    i = i-1

print('\nThe reverse order of elements in a string with -ve Index are:\n')
i = 1
while i <= n:
    print(str1[-i], end=' ')
    i = i+1

# Output:
The elements in a string are:
W e l c o m e   t o   P y t h o n   P r o g r a m 

The reverse order of elements in a string are:
m a r g o r P   n o h t y P   o t   e m o c l e W 

The reverse order of elements in a string with -ve Index are:
m a r g o r P   n o h t y P   o t   e m o c l e W 

# Repeating the Strings:
str1 = 'Core Python'
str2 = str1*2
print('\nThe string repeated 2 times is:\n', str2)

str3 = str1[5:7]*3
print('The sub string repeated 3 times is:\n', str3)

# Output:
The string repeated 2 times is:
 Core PythonCore Python
The sub string repeated 3 times is:
 PyPyPy

# ------------------------------------------------------------------------------------------------------------------------ #

# Concatenating Splitting and Joining of the Strings:
str1 = "Welcome"
str2 = 'to Python'
str3 = str1 + ' ' + str2
print('The concatenated string is:\n', str3)

str1 = "Welcome to Python Program"
str2 = str1.split(' ')
print('The string after split is:\n', str2)

str1 = ['Welcome', 'to', 'Python', 'Program']
sep = '-'
str2 = sep.join(str1)
print('The string after join is:\n', str2)

# Output:
The concatenated string is:
 Welcome to Python

The string after split is:
 ['Welcome', 'to', 'Python', 'Program']

The string after join is:
 Welcome-to-Python-Program

# ------------------------------------------------------------------------------------------------------------------------ #

# Changing the case of Strings:
str1 = "Welcome to PYTHON"
ustr1 = str1.upper()
print('\nThe UPPER case of string is:\n', ustr1)

lstr1 = str1.lower()
print('The lower case of string is:\n', lstr1)

tstr1 = str1.title()
print('The Title case of string is:\n', tstr1)

# Output:
The UPPER case of string is:
 WELCOME TO PYTHON

The lower case of string is:
 welcome to python

The Title case of string is:
 Welcome To Python

# ------------------------------------------------------------------------------------------------------------------------ #

# Sorting the String elements:
list1 = ['Apple', 'Microsoft', 'Dell', 'Canon', 'Tata']
str1 = 'Welcome'
s1 = sorted(str1)
s2 = sorted(list1)
print('\nThe elements of string after sorting:\n', s1)
print('The list of elements after sorting:\n', s2)

# Output:
The elements of string after sorting:
 ['W', 'c', 'e', 'e', 'l', 'm', 'o']
The list of elements after sorting:
 ['Apple', 'Canon', 'Dell', 'Microsoft', 'Tata']

# ------------------------------------------------------------------------------------------------------------------------ #

# String Testing Methods:
st1 = 'abc123xyz'
t1 = isalpha(str1)
t2 = isalnum(str1)
t3 = isdigit(str1)
print('Is the string having at least one alphabet value:', t1)
print('Is the string having alphanumeric value :', t2)
print('Is the string having only numeric digits :', t3)

# Output:
Is the string having at least one alphabet value: True
Is the string having alphanumeric value : True
Is the string having only numeric digits : False

Notes:
In the similar way, we can check the case of the strings using the methods isupper(), islower() and listitle().
Also we can use the method isspace() to check whether the string contains only spaces or not.

# ------------------------------------------------------------------------------------------------------------------------ #

# Removing the lagging and leading spaces from Strings:
str1 = "   Welcome to PYTHON  "
len1 = len(str1)
print('\nThe length of the original string is:', len1)

str2 = str1.lstrip() #Trimming lagging spaces
len2 = len(str2)
print('The length of the string after L-TRIM is:', len2)

str2 = str1.rstrip() #Trimming leading spaces
len2 = len(str2)
print('The length of the string after R-TRIM is:', len2)

str2 = str1.strip() #Trimming both side of spaces
len2 = len(str2)
print('The length of the string after TRIM is:', len2)

# Output:
The length of the original string is: 22
The length of the string after L-TRIM is: 19
The length of the string after R-TRIM is: 20
The length of the string after TRIM is: 17

# ------------------------------------------------------------------------------------------------------------------------ #

# Replacing a substring with another substring in the main string:
str1 = "Hello, Welcome to Python Program"
str2 = str1.replace('o', 'a', 2) # Replace the first 2 instances
print('The string after replacing first 2 instances of "'"o"'" with "'"a"'" is:\n', str2)
str2 = str1.replace('o', 'a')
print('The string after replacing every instances of "'"o"'" with "'"a"'" is:\n', str2)

# Output:
The string after replacing first 2 instances of "o" with "a" is:
 Hella, Welcame to Python Program

The string after replacing every instances of "o" with "a" is:
 Hella, Welcame ta Pythan Pragram

# ------------------------------------------------------------------------------------------------------------------------ #

# Checking the starts with and ends with of a string:
str1 = 'Welcome to Python'
a = str1.startswith('Python')
print(a)
b = str1.endswith('Python')
print(b)

# Output:
False
True

# Checking membership of a substring:
str1 = 'Welcome to Python'
substr1 = 'come'
if substr1 in str1:
    print("\nThe substring "'"{0}"'" exists in main string".format(substr1))
else:
    print("\nThe substring "'"{0}"'" not exists in main string".format(substr1))

# Output:
The substring "come" exists in main string

# ------------------------------------------------------------------------------------------------------------------------ #

# Finding the position of 1st occurrence a Substring using Find() method:
We can find the position of a substring in the main string using the Find() method. The Find() will return '-1' when it does not found the substring in the main string.

str1 = 'Welcome to Python'
sub1 = 'Py'
n1 = str1.find(sub1, 0, len(str1))

if n1 == -1:
    print('The substring not found in the main string')
else:
    print('The substring first found at the position:', n1+1)

# Output:
The substring first found at the position: 12

# Finding the position of 1st occurrence a Substring using Index() method:
We can find the position of a substring in the main string using the Index() method. it return error when it does not found the substring in the main string. We can handle such error with use of try..except method.

str1 = 'Welcome to Python'
sub1 = 'to'
try:
    n1 = str1.index(sub1, 0, len(str1))
except ValueError:
    print('The substring not found in the main string')
else:
    print('The substring first found at the position:', n1+1)

# Output:
The substring first found at the position: 9

# Returning the no. of occurrences of a Substring in main String:
str1 = 'Welcome to Python'
sub1 = 'o'
n1 = str1.count(sub1, 0, len(str1))

if n1 == 0:
    print('The substring not found in the main string')
else:
    print('The substring found {0} times in the main String'.format(n1))

# Output:
The substring found 3 times in the main String

# ------------------------------------------------------------------------------------------------------------------------ #

# Finding the position(s) of each occurrence a Substring in Main string using While loop:
str1 = 'Lab to learn Python too easy'
sub1 = 'to'
flag1 = False
pos = []
i = 0
j = 0
k = 0
n1 = len(str1)

while i <= n1:
    j = str1.find(sub1, i, n1)
    if j != -1:
        pos.append(j+1)
        k = k+1
        i = j+1
        flag1 = True
    else:
        i = i+1

if flag1 == False:
    print('The substring not found in the main string')
else:
    print('The substring found {0} time(s) at the position(s):'.format(k), pos)

# Output:
The substring found 2 time(s) at the position(s): [5, 21]

# Finding the position(s) of each occurrence a Substring in Main string using While loop with Break statement:
str1 = 'Lab to learn Python too easy'
sub1 = 'ea'
flag1 = False
pos = []
i = 0
j = -1
k = 0
n1 = len(str1)
while True:
    j = str1.find(sub1, i, n1)
    if j == -1:
        break
    else:
        pos.append(j+1)
        k = k+1
        i = j+1
        flag1 = True
if flag1 == False:
    print('The substring not found in the main string')
else:
    print('The substring found {0} time(s) at the position(s):'.format(k), pos)

# Output:
The substring found 2 time(s) at the position(s): [9, 25]

# ------------------------------------------------------------------------------------------------------------------------ #

# Finding the position of each occurrence a Substring in a List of Strings using While loop:
list1 = ['Ram', 'Ravi', 'Vikram', 'Ravi', 'Vijay']
sub1 = 'Ravi'
flag1 = False
pos = []
i = 0
j = -1
k = 0

for i in range(len(list1)):
    if sub1 == list1[i]:
        pos.append(i+1)
        k = k+1
        flag1 = True
if flag1 == False:
    print('The substring not found in the list of strings')
else:
    print('The substring found {0} time(s) at the position(s):'.format(k), pos)

# Output:
The substring found 2 time(s) at the position(s): [2, 4]


# Finding the position of each occurrence a Substring in a List of strings provided by the user using While loop:
list1 = []
flag1 = False
pos = []
i = 0
j = -1
n1 = int(input('How Many strings you wish to enter:\n'))
for i in range(n1):
    print('Enter string {0}: '.format(i+1), end=' ')
    list1.append(input())

sub1 = input('Enter substring to search:\n')

for i in range(len(list1)):
    if sub1 == list1[i]:
        pos.append(i+1)
        flag1 = True
if flag1 == False:
    print('The substring not found in the list of strings')
else:
    print('The substring finds at the positions:', pos)

# Input:
How Many strings you wish to enter:
5
Enter string 1:  Raju
Enter string 2:  Ravi
Enter string 3:  Vijay
Enter string 4:  Ravi
Enter string 5:  Vikram
Enter substring to search:
Ravi

# Output:
The substring finds at the positions: [2, 4]

#--------------------------------------------------------------Thanks--------------------------------------------------------------#

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.

Featured Post from this Blog

How to compare Current Snapshot Data with Previous Snapshot in Power BI

How to Dynamically compare two Snapshots Data in Power BI Scenario: Suppose, we have a sample Sales data, which is stored with Monthly Snaps...

Popular Posts from this Blog