Python Day 6- String Functions,Looping-For,ifelse conditions and Task
Guru prasanna
Posted on November 20, 2024
Find():
Searches the string for a specified value and returns the position of where it was found.
Ex:
txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)
Output:
7
So welcome is in 7th position as per indexing.If any other word is given which is not defined then the result will be -1.
Note:In the above example if index function is used instead of find,then it will display "valueerror: substring not found".If defined then output will be same like find function.
Looping:
For loop:
Ex:1
txt = '1234'
for num in txt:
print(num,end=' ')
Output:
1 2 3 4
Ex:2
name = input("Enter Name: ")
print(name)
for alphabet in name:
print(alphabet, end='*')
Output:
Enter Name: guru
guru
g*u*r*u*
Ifelse:
It runs the program with decision based on whether the statement is true or false.
txt = '12a4'
for num in txt:
if num>='0' and num<='9':
print(num,end=' ')
else:
print('Not Decimal',end=' ')
Output:
1 2 Not Decimal 4
In above example 1,2,4 are decimal but a is not a decimal so in output it shows not decimal as per else condition.
Task:
lakshmi Pritha
guru Prasanna
guhanraja
varatharajan
Find:
1: Names starting with letter 'g'
2: Names endings with 'a'
3: Names having space in between
4: Names having more than 9 letters
name=input("Enter names: ")
names=(name).split(",")
for letter in names:
if letter.startswith('g'):
print("Names starts with g are: ",letter)
for ending_letter in names:
if ending_letter.endswith('a'):
print("Names end with a are: ",ending_letter)
for space in names:
for word in space:
if word==' ':
print("Names with space: ",space)
else:
continue
for character in names:
if len(character)>9:
print("Names with more than 9 letters: ",character)
output:
Enter names: guru prasanna,guhanraja,lakshmi pritha,varatharajan
Names starts with g are: guru prasanna
Names starts with g are: guhanraja
Names end with a are: guru prasanna
Names end with a are: guhanraja
Names end with a are: lakshmi pritha
Names with space: guru prasanna
Names with space: lakshmi pritha
Names with more than 9 letters: guru prasanna
Names with more than 9 letters: lakshmi pritha
Names with more than 9 letters: varatharajan
Posted on November 20, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.