0% found this document useful (0 votes)
39 views22 pages

String

The document provides a comprehensive overview of string manipulation in Python, covering topics such as traversing strings, reversing strings, string slicing, and various string functions and methods. It includes examples of programs to demonstrate these concepts, as well as explanations of membership and comparison operators. Additionally, it discusses how to count vowels, uppercase, lowercase, and digits in strings, along with pattern printing and string formatting techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views22 pages

String

The document provides a comprehensive overview of string manipulation in Python, covering topics such as traversing strings, reversing strings, string slicing, and various string functions and methods. It includes examples of programs to demonstrate these concepts, as well as explanations of membership and comparison operators. Additionally, it discusses how to count vowels, uppercase, lowercase, and digits in strings, along with pattern printing and string formatting techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

STRING

MANIPULATION
-RAJAN BANIK
TRAVERSING STRING
• It means accessing the individual characters of string i.e. from first character to
last character.
• Every character in string is at different index position i.e. from 0 to size-1
• For loop can be used to traverse the string very easily
• For .e.g
name="lovely"
for ch in name:
print(ch,'-',end='')

The above code will print l-o-v-e-l-y-


PROGRAM TO READ STRING AND PRINT IN
REVERSE ORDER
string1 = input("Enter any string ")
print("The Reverse of ", string1 ," is :")
length=len(string1)
for ch in range(-1,(-length-1),-1):
print(string1[ch])
The above code will print
Enter any string: karan
n
a
r
a
k
PROGRAM TO INPUT STRING AND PRINT
SHORT FORM

string=input("Enter any string ")


print(string[0],".",end='')
for ch in range(1,len(string)):
if string[ch]==' ':
print(string[ch+1],".",end='')
PROGRAM TO INPUT ANY STRING AND
COUNT HOW MANY VOWELS IN IT
A=“Tom”
B=“Jerry”
C=A+” & ”+B
print(C)
Note: you cannot add number and string using +

Line=“ go”
print(Line*3, ” Govinda”)
Note: you cannot multiply string and string
using * Only number*number or
string*number is allowed
MEMBERSHIP OPERATORS
• Membership operators (in and not in) are used to
check the presence of character(s) in any string.
Example Output
“a” in “python” False
“a" in "java" True
“per" in "operators" True
“men" in "membership" False
"Man" in "manipulation" False
“Pre" not in "presence" True
COMPARISON OPERATORS
• We can apply comparison operators (==, !=,>,<,>=,<=) on string.
Comparison will be character by character.
str1="program"
Comparison of string
str2="python" will be based on
str3="Python" ASCII code of the
characters
Example Output
str1==str2 False Characters Ordinal/
str1!=str2 True ASCII code
A-Z 65-90
str2=="python‟ True 97-122
a-z
str2>str3 True 0-9 48-57
str3<str1 True
STRING SLICING
As we know slice means „part of‟, so slicing is a process of
extracting part of string. In previous chapters we already
discussed that string characters have their unique index
position from 0 to length-1 and -1 to –length(backward)

Forward indexing 0 1 2 3 4 5 6
message W E L C O M E
-7 -6 -5 -4 -3 -2 -1 Backward indexing
>>> str1="wonderful"

STRING SLICING
>>> str1[3:3]
>>> str1[0:6] ''
'wonder' >>> str1[3:4]
>>> str1[0:3] 'd'
'won' >>> str1[-5:-2]
>>> str1[3:6] 'erf'
'der' >>> str1[:-2]
>>> str1[-1:-3] 'wonderf'
'' >>> str1[:4]
>>> str1[-3:-1] 'wond‘
'fu' >>> str1[-3:]
>>> str1[-3:0] 'ful‘
'‘ >>>str1[::-1]
>>>str1[0::2] lufrednow
‘Wnefl’
PATTERN PROGRAMS
Program to print the pattern Program to input name and print
@ as (if name is ‘AAMIR’), output
@@ A
@@@ AA
@@@@ AAM
@@@@@ AAMI
AAM I R
string='#'
pattern='' name=input("Enter any name")
for i in range(5): for i in range(0,len(name)+1):
pattern+=string print(name[0:i])
print(pattern)
STRING FUNCTIONS/METHODS
Function Name Description Example
len(string) This function returns the number of characters in any
string including spaces.

capitalize() This function is used to convert the first letter of


sentence in capital letter.

title() This function is used to convert first letter of


every word in string in capital letters.

upper() This function is used to convert the entire string


in capital letter.

lower() This function is used to convert the entire string in


small letter.
Function Name Description Example
index(substring) This function return index position of
substring. If substring not it returns error
‘substring not found’.

isalnum() This function is used to check where string


contain all character as alphanumeric or
not. Its return is either True or False.

islower() This function return True if all the


characters in string is in small letters.

isupper() This function return True if all the


characters in string is in capital letters.
Both islower() and isupper() will check the
case only for letter, if any symbol present in
string it will be ignored.
Function Name Description Example
count() This function return the number of times substring str
occurs in the given string. If we do not give start
index and end index, then searc hing starts from
index 0 and ends at length of the string.

find() This function is used to search the first


occurrence of the substring in the given string.
Syntax: [Link](sub,start,end)

replace() This function is used to replace all the


occurrences of old string with the new string.
Syntax: [Link](old,new)

split() This function is used to breaks up a string at the


specified separator and returns a list of
substrings.
Function Name Description Example
istitle() This function doesn’t take any arguments. It returns
True if string is properly “title-cased”, else returns False
if the string is not a “title-cased” string or an empty
string.

join() This function returns a string in which the string


elements have been joined by a string separator.

swapcase() This function converts and returns all the


uppercase characters into lowercase and vice
versa of the given string.
endswith() This function returns True if the given string
ends with the specified substring, else returns
False.
startswith() This function returns True if the given string
starts with the specified substring, else returns
False.
isspace() isalpha() isdigit()
It return True if the string It return True if all the It returns True if all the
contains only space. characters in string is characters in string is digit.
alphabet.

• split() : this function is used to split the string


based on delimiter and store the result in the
form of list. Default delimiter is space.
• partition(sep) : this function divides the string in the
form of tuples of 3 elements known a s head, sep
and tail. All the string before sep becomes head a nd
all the string after sep becomes tail. If sep is not
present in the string then everything will becomes he ad ,
sep a n d tail will be empty.
VA R I O U S S T R I P ( ) FUNCTIONS
• strip([chars]) :
it return a copy of string with leading and trailing
whitespaces removed. If c hars is given, it remove characters instead.
• lstrip([chars]) :it return a copy of string with leading whitespaces
removed. If c hars is given, it remove characters instead.
• rstrip([chars]) :it return a copy of string with trailing whitespaces
removed. If c hars is given, it remove characters instead.

• Note: if chars is given in any strip() function, the chars are checked for all the
possible combination that can be formed with the given chars. For e.g. if NOT
is passed as char then NOT, OTN, TON, TNO, ONT,NT like this every possible
combination will be checked.
PROGRAM TO ENTER STRING AND COUNT HOW MANY
UPPERCASE, LOWERCASE, DIGITS, WORDS PRESENT IN IT.
PROGRAM TO ENTER STRING AND FIND THE NUMBER OF
OCCURANCE OF ANY WORD
CONSIDER THE FOLLOWING CODE: WHAT WILL BE THE
OUTPUT IF INPUT IS (i) aabbcc (ii) aaccbb (iii) abcc

string = input("Enter a string :")


count=3 If input is aabbcc, output will be
while True: bbcc
if string[0]=='a': 4
string = string[2:] If input is aaccbb,output will be
elif string[-1] == 'b': cc
string=string[:2] 4
else: If input is abcc,output will be
count+=1 cc
break 4
print(string)
print(count)
WHAT WOULD FOLLOWING EXPRESSION RETURN?
a) “Hello World”.upper().lower() OUTPUT?
b) “Hello World”.lower().upper() (a) s="0123456789"

c) “Hello World”.find(“Wor”,1,6) print(s[3],',',s[0:3],'-',s[2:5])


print(s[:3],',',s[3:],'-',s[3:100])
d) “Hello World”.find(„Wor‟)
print(s[20:],',',s[2:1],'-',s[1:1])
e) “Hello World”.find(„wor‟)
f) “Hello World”.isalpha() (b) y=str(123)
x="hello"*3 print(x,y)
g) “Hello World”.isalnum()
x = "hello" + "world"
h) “1234”.isdigit() y=len(x) print(y,x)
i) “123GH”.isdigit()
RAJAN BANIK
PGT- COMPUTER SCIENCE
[Link]@[Link]

You might also like