0% found this document useful (0 votes)
2 views

Python Chap 2

The document provides an overview of flow control statements in Python, including conditional statements (if, if-else, if-elif-else) and iterative statements (for and while loops). It includes examples and syntax for each type of statement, as well as explanations of break, continue, and pass statements. Additionally, it covers string data types and how to access string characters using indexing and slicing.

Uploaded by

tokejidnyesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Chap 2

The document provides an overview of flow control statements in Python, including conditional statements (if, if-else, if-elif-else) and iterative statements (for and while loops). It includes examples and syntax for each type of statement, as well as explanations of break, continue, and pass statements. Additionally, it covers string data types and how to access string characters using indexing and slicing.

Uploaded by

tokejidnyesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Anand Komiripalem

Flow Control Statement


 Flow control describes the order in which statements will be
executed at runtime.
Anand Komiripalem

Flow Control Statement


Conditional Statements:

 if
 if – else
 if – elif – else

If: If condition is true then only the statement will be executed


Syntax: if condition : statement
(or)
if condition :
statement-1
statement-2
statement-3
Anand Komiripalem

Flow Control Statements


Eg:
Output:
name=input("Enter Name:") Enter Name: Anand
if name==“Anand" : Hello Anand Good Morning
print("Hello Anand Good Morning") How are you!!!
print("How are you!!!") ------------------------------
Enter Name: Ravi
How are you!!!
if – else:
if condition:
Action-1
else:
Action-2

 if condition is true then Action-1 will be executed otherwise Action-2 will


be executed
Anand Komiripalem

Flow Control Statements


Eg: Output:
name=input("Enter Name:") Enter Name: anand
if name==“anand" : Hello anand Good morning
print("Hello anand Good Morning") How are you
else: ------------------------------------
print("Hello Guest Good Moring") Enter Name: anand
print("How are you!!!")
Hello anand Good morning
How are you

if-elif-else: Based on the condition corresponding action will be executed.

if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
...
else:
Default Action
Anand Komiripalem

Flow Control Statements


Eg:
brand=input("Enter Your Brand:")
Output:
if brand=="RC" :
Enter Your Brand: RC
print("It is childrens brand") It is childrens brand
elif brand=="KF": ------------------------------------
print("It is not that much kick") Enter Your Brand: OF
elif brand=="FO": Other Brands are not
recommended
print("Buy one get Free One")
else :
print("Other Brands are not recommended“)

Note: There is no switch statement in Python


Anand Komiripalem

Flow Control Statements


 Write a Program to find Biggest of given 2 Numbers from the Command
Prompt?

n1=int(input("Enter First Number:"))


n2=int(input("Enter Second Number:")) Output:
if n1>n2: Enter First Number: 20
print("Biggest Number is:",n1) Enter Second Number: 15
else :
Biggest Number is: 20
print("Biggest Number is:",n2)
Anand Komiripalem

Flow Control Statements


 Write a Program to find Biggest of given 3 Numbers from the Command
Prompt?

n1=int(input("Enter First Number:"))


n2=int(input("Enter Second Number:")) Output:
n3=int(input("Enter Third Number:")) Enter First Number: 340
Enter Second Number: 125
if n1>n2 and n1>n3: Enter Third Number: 341
print("Biggest Number is:",n1)
elif n2>n3: Biggest Number is: 341
print("Biggest Number is:",n2)
else :
print("Biggest Number is:",n3)
Anand Komiripalem

Assignment
 Write a program to check whether the given number is even or
odd?
 Write a Program to Check whether the given Number is in
between 1 and 100?
 Write a program to find smallest of given 3 numbers?
Anand Komiripalem

Flow Control Statements


Iterative Statements:
 If we want to execute a group of statements multiple times then
we should go for Iterative statements.
 Python supports 2 types of iterative statements.
1) for loop
2) while loop

for loop:
 If we want to execute some action for every element present in
some sequence (it may be string or collection) then we should go
for - for loop.
Syntax: for x in sequence:
Body
 Where sequence can be string or any collection
 Body will be executed for every element present in the sequence.
Anand Komiripalem

Flow Control Statements


Eg 1: To print characters present in the given string Output:
s=“Anand" A
n
for x in s :
a
print(x) n
d

Eg 2: To print characters present in string index wise:


s=input("Enter some String: ") Output:
i=0 Enter some String: anand
for x in s : The character @ 0 index is a
print("The character @ ",i,"index is :",x) The character @ 1 index is n
The character @ 2 index is a
i=i+1
The character @ 3 index is n
The character @ 4 index is d
Flow Control Statements
 Eg 3: To display numbers from 0 to 10
for x in range(11) :
print(x)

 Eg 4: To display odd numbers from 0 to 20


 Eg 5: To display numbers from 10 to 1 in descending order
for x in range(10,0,-1) :
print(x)
 Eg 6: To print sum of numbers present inside list
list = eval(input("Enter List:"))
sum=0;
Output:
for x in list: Enter List: [10,20,30,40]
sum=sum+x; The Sum=100
print("The Sum=",sum)
Anand Komiripalem

Flow Control Statements


While Loop:
 If we want to execute a group of statements iteratively until some
condition false, then we should go for while loop.

Syntax: while condition :


body
Eg: To print numbers from 1 to 10 by using while loop

x=1
while x <= 10:
print(x)
x = x+1
Anand Komiripalem

Flow Control Statements


Eg: To display the sum of first n numbers
n=int(input("Enter number:"))
sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print("The sum of first",n,"numbers is :",sum)

Eg: Write a program to prompt user to enter some name until entering Your name

name=""
while name!=“anand":
name=input("Enter Name:")
print("Thanks for confirmation")
Anand Komiripalem

Flow Control Statements


Infinite Loops:
i=0;
while True :
i=i+1;
print("Hello",i)

Nested Loops:
Loop inside another loop is known as nested loops.
for i in range(4):
for j in range(4):
print("i=",i," j=",j)
Anand Komiripalem

Flow Control Statements


 Write a Program to display *'s in Right Angled Triangle Form
n = int(input("Enter number of rows:")) Output:
for i in range(1,n+1):
for j in range(1,i+1): *
**
print("*",end=" ")
***
print() ****
*****
Alternate way:

n = int(input("Enter number of rows:"))


for i in range(1,n+1):
print("* " * i)
Anand Komiripalem

Flow Control Statements


Write a Program to display *'s in Pyramid Style
*
n = int(input("Enter number of rows:")) **
for i in range(1,n+1): ***
print(" " * (n-i),end="") ****
print("* "*i) *****
******

n=int(input("Enter the number of rows: "))


for i in range(1,n+1):
print(" "*(n-i),end="") Enter the number of rows: 6
for j in range(1,i+1): 1
print(j,end=" ") 121
for k in range(i-1,0,-1): 12321
print(k,end=" ") 1234321
print()
123454321
12345654321
Anand Komiripalem

Flow Control Statements


n=int(input("Enter the number of rows: ")) Enter the number of rows: 6
for i in range(1,n+1): A
print(" "*(n-i),end="") BAB
for j in range(1,i):
CBABC
DCBABCD
print(chr(i-j+65),end=" ")
EDCBABCDE
for k in range(0,i):
FEDCBABCDEF
print(chr(k+65),end=" ")
print()

Enter the number of rows: 7


n=int(input("Enter the number of rows: "))
1234567
for i in range(1,n+1): 123456
print(" "*(i-1),end="") 12345
for j in range(1,n+2-i): 1234
print(j,end=" ") 123
print() 12
1
Anand Komiripalem

Flow Control Statements


Anand Komiripalem

Flow Control Statements


Transfer Statements:
break: We use break statement inside loops to break loop execution based
on some condition.
Eg1:
0
for i in range(10):
1
if i==7:
print("processing is enough..plz break") 2
break 3
print(i) 4
5
Eg 2: 6
cart=[10,20,600,60,70]
for item in cart:
if item>500: 10
print("insurance must be required") 20
break
insurance must be required
print(item)
Anand Komiripalem

Flow Control Statements


continue:
We use continue statement to skip current iteration and continue next iteration.

Eg 1:To print odd numbers in the range 0 to 9


1
for i in range(10): 3
if i%2==0: 5
continue 7
print(i) 9

Eg 2:
cart=[10,20,500,700,50,60] 10
for item in cart: 20
if item>=500: cannot process item : 500
print("cannot process item :",item) cannot process item : 700
continue 50
print(item) 60
Anand Komiripalem

Flow Control Statements

numbers=[10,20,0,5,0,30]
for n in numbers:
if n==0:
print(“please wakeup … cannt divide by zero")
continue
print("100/{} = {}".format(n,100/n))
100/10 = 10.0
100/20 = 5.0
please wakeup … cannt divide by zero g
100/5 = 20.0
please wakeup … cannt divide by zero
100/30 = 3.3333333333333335
Anand Komiripalem

Flow Control Statements


pass statement:
 pass is a keyword in Python.
 In our program syntactically if a block is required which won't do
anything then we can define that empty block with pass keyword.
 pass is an empty statement | null statement | it won't do anything

for i in range(50):
0
if i%9==0:
9
print(i)
else:pass 18
27
36
45
Anand Komiripalem

Flow Control Statements


else with loops:
 Python supports else condition with loops also
 else block in for/while is executed only when the loop is NOT
terminated by a break statement.

cart=[10,20,600,30,40,50]
for item in cart: 10
20
if item>=500:
We cannot process this order
print("We cannot process this order")
break
print(item)
else:
print("Congrats ...all items processed successfully")

 If the loop is terminated using break then else will not be executed.
Anand Komiripalem

Flow Control Statements


cart=[10,20,30,40,50]
for item in cart:
if item>=500:
print("We cannot process this order")
break
print(item)
else:
print("Congrats ...all items processed successfully")

10
20
30
40
50
Congrats ...all items processed successfully
Anand Komiripalem

Flow Control Statements


What is the difference between for loop and while loop in Python?

 We can use loops to repeat code execution


 Repeat code for every item in sequence for loop
 Repeat code as long as condition is true  while loop

del Statement:
• del is a keyword in Python.
• We can delete variable by using del keyword
x = 10
print(x) #10
del x
print(x) #error
Anand Komiripalem

STRING
DATA TYPE
Anand Komiripalem

String Data Type


 String is a sequence of characters
 In python string is written with in single quotes or double quotes
 The most commonly used data type (object) in any project.
Syntax: s=‘anand’
s=“anand”

Note: In most of other languages like C, C++, Java, a single character with in
single quotes is treated as char data type value. But in Python we are
not having char data type. Hence it is treated as String only.

 We can define multi-line String literals by using triple single or double


quotes.
s = ''‘Advanto
software
Pvt Ltd'''
Anand Komiripalem

String Data Type


Which of the following declaration is valid

s = 'This is ' single quote symbol'  Invalid


s = 'This is \' single quote symbol'  Valid
s = "This is ' single quote symbol"  Valid
s = 'This is " double quotes symbol'  Valid
s = 'The "Python Notes" by ‘anand' is understandable'  Invalid
s = "The "Python Notes" by ‘anand' is very helpful"  Invalid
s = 'The \"Python Notes\" by \’anand\' is very helpful‘ Valid
s = '''The "Python Notes" by ‘anand' is very helpful'''  Valid
Anand Komiripalem

String Data Type


Access Characters of a String :
 We can access characters of a string by using the following ways.
1) By using index
2) By using slice operator

Accessing Characters By using Index:


 Python supports both +ve and -ve Index.
 +ve Index means Left to Right (Forward Direction)
 -ve Index means Right to Left (Backward Direction)
Eg: s = Advanto'
s[0] = A
s[4] = n
s[20] = Error
Note: If we are trying to access characters of a string with out of range
index then we will get error saying: IndexError
Anand Komiripalem

String Data Type


Write a Program to Accept some String from the Keyboard and display
its Characters by negative Index wise

s=input("Enter Some String:")


i=0
for x in s:
print("The character present at positive index {} and at negative index {} is
{}".format(i,i-len(s),x))
i=i+1

Enter Some String:anand


The character present at positive index 0 and at negative index -5 is a
The character present at positive index 1 and at negative index -4 is n
The character present at positive index 2 and at negative index -3 is a
The character present at positive index 3 and at negative index -2 is n
The character present at positive index 4 and at negative index -1 is d
Anand Komiripalem

string Data Type


Accessing Characters by using Slice Operator:

Syntax: s[begin-index: end-index-1: step]

Begin Index: From where we have to consider slice (substring)


End Index: We have to terminate the slice (substring) at endindex-1
Step: Incremented Value.

Note:
 If we are not specifying begin index then it will consider from beginning of
the string.
 If we are not specifying end index then it will consider up to end of the
string.
 The default value for step is 1.
Anand Komiripalem

string Data Type


Eg:

s="Learning Python is very very easy!!!"


s[1:7:1] # 'earnin'
s[1:7] # 'earnin'
s[1:7:2] # 'eri'
s[:7] # 'Learnin'
s[7:] # 'g Python is very very easy!!!'
s[::] # 'Learning Python is very very easy!!!'
s[:] # 'Learning Python is very very easy!!!'
s[::-1] # '!!!ysae yrev yrev si nohtyP gninraeL'
Anand Komiripalem

string Data Type


Mathematical Operators for String:
We can apply the following mathematical operators for Strings.
+ operator for concatenation
*  operator for repetition
Ex:
print(“advanto"+"software")  advantosoftware
print(“anand"*2)  anandanand

Note:
 To use + operator for Strings, compulsory both arguments should be str
type.
 To use * operator for Strings, compulsory one argument should be str and
other argument should be int.
Anand Komiripalem

String Data Type


len() Function:
 A built in function in python
 Used to find the number of characters present in the string.

Eg:
s = ‘anand'
print(len(s))  5
Anand Komiripalem

String Data Type


Write a Program to access each Character of String in Forward and
Backward Direction by using while Loop?

s = "Learning Python is very easy !!!"


n = len(s)
Alternate way
i=0
----------------------
print("Forward direction") s = "Learning Python is easy !!!"
while i<n: print("Forward direction")
print(s[i],end=' ') for i in s:
i +=1 print(i,end=' ')
print("Backward direction") print("Forward direction")
i = -1 for i in s[::]:
while i >= -n: print(i,end=' ')
print(s[i],end=' ') print("Backward direction")
i = i-1 for i in s[::-1]:
print(i,end=' ')
Anand Komiripalem

String Data Type


Checking Membership:
We can check whether the character or string is the member of another
string or not by using in and not in operators

s = ‘Anand'
print('d' in s)  True
print('z' in s)  False
Output:
------------------------------------------
s = input("Enter main string:") Enter main string:
subs = input("Enter sub string:") Advantosoftwaresolutions
if subs in s:
Enter sub string: solution
print(subs,"is found in main string")
Solution is found in main string
else:
print(subs,"is not found in main string")
Anand Komiripalem

String Data Type: String Comparison


Comparison of Strings:
 We can use comparison operators (<, <=, >, >=) and equality
operators (==, !=) for strings.
 Comparison will be performed based on alphabetical order

Output:
s1=input("Enter first string:")
s2=input("Enter Second string:") Enter First String: anand
if s1==s2: Enter Second String: anand
print("Both strings are equal") Both Strings are equal
-----------------------------------
elif s1<s2:
Enter First String: anand
print("First String is less than Second ") Enter Second String: Ravi
else: First String is less than Second
print("First is greater than Second ")
Anand Komiripalem

String Data Type: Removing Spaces from String


Removing Spaces from the String:
We can use the following 3 methods
rstrip()  To remove spaces at right hand side
lstrip()  To remove spaces at left hand side
strip()  To remove spaces on both sides

city=input("Enter city Name:")


Output:
scity=city.strip()
if scity=='Hyderabad': Enter city name: Hyderabad
print("Hello Hyderbadi..Adab")
elif scity=='Chennai': Hello Hyderbadi..Adab
print("Hello Madrasi...Vanakkam")
elif scity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
Anand Komiripalem

String Data Type: Finding Substrings


Finding Substrings:
We can use the following 4 methods/functions

For Forward Direction:


find()
index()

For Backward Direction:


rfind()
rindex()
Anand Komiripalem

String Data Type: Finding Substrings


find():
Returns index of first occurrence of the given substring. If the given
string is not available then it returns -1
Syntax: find(substring)

Eg:
s="Learning Python is very easy"
print(s.find("Python")) #9
print(s.find("Java")) # -1
print(s.find("r")) #3
print(s.rfind("r")) #21

Note: By default find() method can search total string. We can also
specify the boundaries to search.
Anand Komiripalem

String Data Type: Finding Substrings


find(substring,begin,end-1)
It will always search from begin index to end-1 index.

s='anand komiripalem works in advanto software'


s.find('a') #0
s.find('a',7,15) #13
s.find('z',7,15) #-1

index():
index() method is exactly same as find() method except that if the specified
substring is not available then we will get ValueError.

Consider the same above example and replace find() with index()
Anand Komiripalem

String Data Type: Finding Substrings


Program to display all Positions of Substring in a given main String

s=input("Enter main string:")


Output:
subs=input("Enter sub string:“)
p=-1 Enter main string:
abaabbbaabbbabbbab
n=len(s)
Enter sub string: a
while True: Found at position 0
p=s.find(subs,p+1,n) Found at position 2
if p==-1: Found at position 3
break Found at position 7
print("Found at position",p) Found at position 8
Found at position 12
Found at position 16
Anand Komiripalem

String Data Type: Counting String


Counting substring in the given String:
 We can find the number of occurrences of substring present in the given
string by using count() function.

 s.count(substring)  It will search through out the string.


 s.count(substring, begin, end)  It will search from begin index to end-1
index.
Ex:
s="abcabcabcabcadda“
print(s.count('a')) #6
print(s.count('ab')) #4
print(s.count('a',3,7)) #2
Anand Komiripalem

String Data Type: Replacing Strings


Replacing a String with another String:
 replace() function is used to replace every occurrence of old String
with new String.
Syntax: replace(oldstring, newstring)

Eg 1:
s = "Learning Python is very difficult"
s1 = s.replace("difficult","easy")
print(s1) # Learning Python is very easy

Eg 2:
s = "ababababababab"
s1 = s.replace("a","b")
print(s1) #bbbbbbbbbbbbbb
Anand Komiripalem

String Data Type: Replacing Strings


String Objects are Immutable then how we can change the Content by
using replace() Method
 Once we creates string object, we cannot change the content. This non
changeable behavior is nothing but immutability. If we are trying to change
the content by using any method, then with those changes a new object will
be created and changes won't be happened in existing object.
 Hence with replace() method also a new object got created but existing
object won't be changed.

Eg:
s = "abab"
s1 = s.replace("a","b")
print(s,"is available at :",id(s)) #abab is available at : 4568672
print(s1,"is available at :",id(s1)) #bbbb is available at : 4568704
Anand Komiripalem

String Data Type: Splitting String


 We can split the given string according to specified separator by using
split() method
Syntax: split(separator)
 The default separator is space. But we can have our own separator
 The return type of split() method is List.

Ex: Output:
s=“Advanto Software Pvt Ltd" Advanto
l=s.split() Software
for x in l: Pvt
print(x) Ltd
Ex:2
Output:
s="22-02-2017"
l=s.split('-') 22
for x in l: 02
print(x) 2017
Anand Komiripalem

String Data Type: String Join


Joining of Strings:
 We can join a Group of Strings or List or Tuple with respect to the given
Separator.
Syntax: seperator.join(group of strings)

Ex:
x='-'.join("Hai how are you")
print(x) #H-a-i- -h-o-w- -a-r-e- -y-o-u

s="how"
t=" ".join(s)
print(t) #h o w

Eg :
t = ('sunny', 'bunny', 'chinny')
s = '-'.join(t)
print(s) #sunny-bunny-chinny
Anand Komiripalem

String Data Type: Changing Case of a String


 We can change case of a string by using the following methods.
 upper()  To convert all characters to upper case
 lower()  To convert all characters to lower case
 swapcase()  converts all lower case to upper case and all upper case to
lower case
 title()  converts every first letter in a word to upper case
 capitalize()  converts first letter to uppercase and all the remaining to
lowercase

Ex:
s = 'learning Python is Easy'
print(s.upper()) #LEARNING PYTHON IS EASY
print(s.lower()) #learning python is easy
print(s.swapcase()) #LEARNING pYTHON IS eASY
print(s.title()) #Learning Python Is Easy
print(s.capitalize()) #Learning python is easy
Anand Komiripalem

String Data Type: String Checking


Checking Starting and Ending Part of the String:
 Python contains the following methods for this purpose
 startswith(substring)
 endswith(substring)

Ex:
s = 'learning Python is very easy'
print(s.startswith('learning')) #True
print(s.endswith('learning')) #False
print(s.endswith('easy')) #True
Anand Komiripalem

String Data Type: Checking Character type


To Check Type of Characters Present in a String:

 isalnum(): Returns True if the characters are alphanumeric( a to z , A


to Z ,0 to9 )
 isalpha(): Returns True if all characters are only alphabets (a to z,A
to Z)
 isdigit(): Returns True if all characters are only digits ( 0 to 9)
 islower(): Returns True if all characters are lower case alphabet
symbols
 isupper(): Returns True if all characters are upper case alphabet
symbols
 istitle(): Returns True if string is in title case
 isspace(): Returns True if string contains only spaces
Anand Komiripalem

String Data Type: Checking Character type


print("Anand786".isalnum()) #True
print("anand786".isalpha()) #False
print("anand".isalpha()) # True
print("anand".isdigit()) # False
print('786786'.isdigit()) # True
print('abc'.islower()) #True
print('Abc'.islower()) # False
print('abc123'.islower()) #True
print('ABC'.isupper()) #True
print('Learning python is Easy'.istitle()) # False
print('Learning Python Is Easy'.istitle()) #True
print(' '.isspace()) #True
Anand Komiripalem

String Data Type: Checking Character type


 Program to accept string from user and display its type

Eg:
Output:
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numeric Character") Enter any character: Hai
if s.isalpha(): Alpha Numeric Character
print("Alphabet character")
elif s.islower(): Enter any character: HELLO
print("Lower case alphabet character")
Alpha Numeric Character
elif s.isupper():
print("Upper case alphabet character") Upper case alphabet character
else:
print("it is a digit")
elif s.isspace():
print("It is space character")
else:
print("Non Space Special Character")
Anand Komiripalem

String Data Type: String Formatting


 We can format the strings with variable values by using replacement
operator {} and format() method

Ex:
name = 'anand'
salary = 10000
age = 48
print("{} 's salary is {} and his age is {}".format(name,salary,age))
print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))

Output:
anand 's salary is 10000 and his age is 48
anand 's salary is 10000 and his age is 48
anand 's salary is 10000 and his age is 48
Anand Komiripalem

String Data Type: String Programs


 Write a Program to Reverse the given String
input: Anand Output: dnanA

s = input("Enter Some String:")


print(s[::-1])

Alternate Way:
s = input("Enter Some String:")
print(''.join(reversed(s)))

Alternate Way:
s = input("Enter Some String:")
i=len(s)-1
target=''
while i>=0:
target=target+s[i]
i=i-1
print(target)
Anand Komiripalem

String Data Type: String Programs


 Program to Reverse Order of Words
Input: Learning Python is very Easy
Output: Easy Very is Python Learning

s=input("Enter Some String:")


l=s.split()
l1=[]
i=len(l)-1
while i>=0:
l1.append(l[i])
i=i-1
output=' '.join(l1)
print(output)
Anand Komiripalem

String Data Type: String Programs


 Program to Reverse Internal Content of each Word
Input: Advanto Software Pvt Ltd
Output: otnavdA erawtfoS tvP dtL

s=input("Enter Some String:")


l=s.split()
l1=[]
i=0
while i<len(l):
l1.append(l[i][::-1])
i=i+1
output=' '.join(l1)
print(output)
Anand Komiripalem

String Data Type: String Programs


 Write a Program to Print Characters at Odd Position and Even Position for the given
String?

s = input("Enter Some String:")


print("Characters at Even Position:",s[0::2])
print("Characters at Odd Position:",s[1::2])

s=input("Enter Some String:")


i=0 Output:
print("Characters at Even Position:") Enter Some String:Hai How are you
while i< len(s):
print(s[i],end=',')
i=i+2 Characters at Even Position:
print() H,i,H,w,a,e,y,u,
print("Characters at Odd Position:") Characters at Odd Position:
i=1 a, ,o, ,r, ,o,
while i< len(s):
print(s[i],end=',')
i=i+2
Anand Komiripalem

String Data Type: String Programs


 Program to Merge Characters of 2 Strings into a Single String by taking Characters
alternatively
Input: s1 = "ravi" Output: rtaevjia
s2 = “teja"

s1=input("Enter First String:")


s2=input("Enter Second String:")
output=''
i,j=0,0
while i<len(s1) or j<len(s2):
if i<len(s1):
output=output+s1[i]
i+=1
if j<len(s2):
output=output+s2[j]
j+=1
print(output)
Anand Komiripalem

String Data Type: String Programs


 Write a Program to Sort the Characters of the String, First Alphabet Symbols followed by
Numeric Values
Input: B4A1D3 Output: ABD134

s=input("Enter Some String:")


s1=s2=output=''
for x in s:
if x.isalpha():
s1=s1+x
else:
s2=s2+x
for x in sorted(s1):
output=output+x
for x in sorted(s2):
output=output+x
print(output)
Anand Komiripalem

String Data Type: String Programs


Input: a4b3c2 Output: aaaabbbcc

s=input("Enter Some String:")


output=''
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
output=output+previous*(int(x)-1)
print(output)
Anand Komiripalem

String Data Type: String Programs


Write a Program to perform the following Activity
Input: a4k3b2 Outpt: aeknbd

s=input("Enter Some String:")


output=''
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
output=output+chr(ord(previous)+int(x))
print(output)

Note:
chr(unicode)  The corresponding character
ord(character)  The corresponding unicode value
Anand Komiripalem

String Data Type: String Programs


Input: ABCDABBCDABBBCCCDDEEEF Output: ABCDEF

s = input("Enter Some String:")


l=[]
for x in s:
if x not in l:
l.append(x)
output=''.join(l)
print(output)

You might also like