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

V.M.Prabhakaran, Department of Cse, KIT-Coimbatore: Problem Solving and Python Programming 1

The document discusses strings in Python, including that strings are immutable sequences of characters that can be manipulated using built-in functions and methods, it covers common string operations like concatenation, slicing, formatting, and searching/testing characters within a string. Examples are provided to demonstrate various string functions and methods in Python like len(), upper(), lower(), find(), replace(), and more.

Uploaded by

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

V.M.Prabhakaran, Department of Cse, KIT-Coimbatore: Problem Solving and Python Programming 1

The document discusses strings in Python, including that strings are immutable sequences of characters that can be manipulated using built-in functions and methods, it covers common string operations like concatenation, slicing, formatting, and searching/testing characters within a string. Examples are provided to demonstrate various string functions and methods in Python like len(), upper(), lower(), find(), replace(), and more.

Uploaded by

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

V.M.

Prabhakaran,
Department Of Cse,
KIT- Coimbatore
Problem Solving and Python Programming 1
Strings: string slices, immutability,
string functions and methods, string
module

Problem Solving and Python Programming 2


Strings
• String is a sequence of characters.
• String may contain alphabets, numbers and
special characters.
• Usually strings are enclosed within a single
quotes and double quotes.
• Strings is immutable in nature.
• Example:
a=„hello world‟
b=“Python”
Problem Solving and Python Programming 3
Inbuilt String functions
• Python mainly contains 3 inbuilt string functions.
• They are
– len()
– max()
– min()
• len()- Find out the length of characters in string
• min()- Smallest value in a string based on ASCII values
• max()- Largest value in a string based on ASCII values

Problem Solving and Python Programming 4


What is ASCII values

Problem Solving and Python Programming 5


Example for Inbuilt string functions
name=input("Enter Your name:")
print("Welcome",name)

print("Length of your name:",len(name))


print("Maximum value of chararacter in your name",
max(name))
print("Minimum value of character in your name",min(name))

Problem Solving and Python Programming 6


OUTPUT
Enter Your name:PRABHAKARAN
Welcome PRABHAKARAN
Length of your name: 11
Maximum value of chararacter in your name R
Minimum value of character in your name A

Problem Solving and Python Programming 7


Strings Concatenation
• The + operator used for string concatenation.
Example:
a=“Hai”
b=“how are you”
c=a+b

print(c)

Problem Solving and Python Programming 8


Operators on String
• The Concatenate strings with the “*” operator
can create multiple concatenated copies.
• Example:
>>> print("Python"*10)
PythonPythonPythonPythonPythonPython
PythonPythonPythonPython

Problem Solving and Python Programming 9


String Slicing
• Slicing operation is used to return/select/slice
the particular substring based on user
requirements.
• A segment of string is called slice.
• Syntax: string_variablename [ start:end]

Problem Solving and Python Programming 10


String Slice example
H e l l o
s=“Hello” 0 1 2 3 4
-5 -4 -3 -2 -1

Problem Solving and Python Programming 11


Strings are immutable
• Strings are immutable character sets.
• Once a string is generated, you cannot change
any character within the string.

Problem Solving and Python Programming 12


String Comparision
• We can compare two strings using comparision
operators such as ==, !=, <,<=,>, >=
• Python compares strings based on their
corresponding ASCII values.

Problem Solving and Python Programming 13


Example of string comparision
str1="green"
str2="black"
print("Is both Equal:", str1==str2)
print("Is str1> str2:", str1>str2)
print("Is str1< str2:", str1<str2)
OUTPUT:

Is both Equal: False


Is str1> str2: True
Is str1< str2: False
Problem Solving and Python Programming 14
String formatting operator
• String formatting operator % is unique to
strings.
• Example:
print("My name is %s and i secured %d
marks in python” % ("Arbaz",92))
• Output:
My name is Arbaz and i secured 92 marks in
python
Problem Solving and Python Programming 15
String functions and methods
len() min() max() isalnum() isalpha()

isdigit() islower() isuppe() isspace() isidentifier()

endswith() startswith() find() count() capitalize()

title() lower() upper() swapcase() replace()

center() ljust() rjust() center() isstrip()

rstrip() strip()

Problem Solving and Python Programming 16


i) Converting string functions
captitalize() Only First character capitalized

lower() All character converted to lowercase

upper() All character converted to uppercase

title() First character capitalized in each word

swapcase() Lower case letters are converted to


Uppercase and Uppercase letters are
converted to Lowercase

replace(old,new) Replaces old string with nre string

Problem Solving and Python Programming 17


Program:
str=input("Enter any string:")
print("String Capitalized:", str.capitalize())
print("String lower case:", str.lower())
print("String upper case:", str.upper())
print("String title case:", str.title())
print("String swap case:", str.swapcase())
print("String replace case:",str.replace("python","python programming"))

Output:

Enter any string: Welcome to python


String Capitalized: Welcome to python
String lower case: welcome to python
String upper case: WELCOME TO PYTHON
String title case: Welcome To Python
String swap case: wELCOME TO PYTHON
String replace case: Welcome to python programming
Problem Solving and Python Programming 18
ii)Formatting String functions
center(width) Returns a string centered in a field of given width

ljust(width) Returns a string left justified in a field of given width

rjust(width) Returns a string right justified in a field of given width

format(items) Formats a string

Problem Solving and Python Programming 19


Program:
a=input("Enter any string:")
print("Center alignment:", a.center(20))
print("Left alignment:", a.ljust(20))
print("Right alignment:", a.rjust(20))

Output:

Problem Solving and Python Programming 20


iii) Removing whitespace
characters
Returns a string with
lstrip() leading whitespace
characters removed
Returns a string with
trailing whitespace
rstrip()
characters removed

Returns a string with


leading and trailing
strip() whitespace characters
removed

Problem Solving and Python Programming 21


Program
a=input("Enter any string:")
print("Left space trim:",a.lstrip())
print("Right space trim:",a.rstrip())
print("Left and right trim:",a.strip())
Output:

Problem Solving and Python Programming 22


iv) Testing String/Character
Returns true if all characters in string are alphanumeric and there is
isalnum()
atleast one character

Returns true if all characters in string are alphabetic


isalpha()

Returns true if string contains only number character


isdigit()

Returns true if all characters in string are lowercase letters


islower()

Returns true if all characters in string are uppercase letters


isupper()

isspace() Returns true if string contains only whitespace characters.


Problem Solving and Python Programming 23
Program
a=input("Enter any string:")
print("Alphanumeric:",a.isalnum())
print("Alphabetic:",a.isalpha())
print("Digits:",a.isdigit())
print("Lowecase:",a.islower())
Output:
print("Upper:",a.isupper())

Problem Solving and Python Programming 24


v) Searching for substring
Endswith() Returns true if the strings ends with the substring

Returns true if the strings starts with the substring


Startswith()

Returns the lowest index or -1 if substring not found


Find()

Count() Returns the number of occurrences of substring

Problem Solving and Python Programming 25


Program
a=input("Enter any string:")
print("Is string ends with thon:", a.endswith("thon"))
print("Is string starts with good:", a.startswith("good"))
print("Find:", a.find("ython"))
print("Count:", a.count(“o"))

Output:

Enter any string : welcome to python


Is string ends with thon: True
Is string starts with good: False
Find: 12
Count: 3
Problem Solving and Python Programming 26
String Modules
• String module contains a number of functions to
process standard Python strings
• Mostly used string modules:
string.upper()
string.upper()
string.split()
string.join()
string.replace()
string.find()
string.count()
Problem Solving and Python Programming 27
Example
import string
text="Monty Python Flying Circus"
print("Upper:", string.upper(text))
print("Lower:", string.lower(text))
print("Split:", string.split(text))
print("Join:", string.join(string.split(test),"+"))
print("Replace:", string.replace(text,"Python", "Java"))
print("Find:", string.find(text,"Python"))
print("Count", string.count(text,"n"))
Problem Solving and Python Programming 28
Output
Upper: “MONTY PYTHON FLYING CIRCUS”
Lower: “monty python flying circus”
Split: [„Monty‟, „Python‟, „Flying‟, „Circus‟]
Join : Monty+Python+Flying+Circus
Replace: Monty Java Flying Circus
Find: 7
Count: 3

Problem Solving and Python Programming 29

You might also like