0% found this document useful (0 votes)
2 views42 pages

Strings in Python

Uploaded by

AVNI ADHIKARI
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)
2 views42 pages

Strings in Python

Uploaded by

AVNI ADHIKARI
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

PYTHON STRINGS

STRING MANIPULATION
STRINGS

• Introduction to strings
• Indexing
• String Operations (concatenation, repetition, membership
and slicing)
• Traversing a string using loops
• Build-in-functions
In python, consecutive sequence of characters is known as a string.
Strings are characters enclosed in quotes of any type – single quotation
marks (‘ ‘), double (“ “) and triple quotation marks(‘’’ ‘’’) or (“”” “””).
You can assign a multiline string to a variable by using three quotes:

a = ""”Python strings are used to single character or


multiple characters."""
print(a)

An empty string is a string that has zero or no character, like “ “.


Python strings are immutable.
STRINGS ARE IMMUTABLE

Strings are immutable means that the contents of the string


cannot be changed after it is created.
Example >>>str='honesty’
>>>str[2]='p’
TypeError: 'str' object does not support item assignment
Python does not allow the programmer to change a character in a
string. As shown in the above example, str has the value „honesty‟.
An attempt to replace „n‟ in the string by ‟p‟ displays a TypeError.
SUBSCRIPT (INDEX)

An individual character in a string is accessed using a


subscript (index).
The subscript should always be an integer (positive or
negative).
A subscript starts from 0 to (length -1) in forward direction
and -1, -2, -3 , to length in backward direction.
STRING LENGTH

To get the length of a string, use the len() function.


Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
13
TRAVERSING A STRING

Traversing a string means accessing all the elements of the string one after
the other by using the subscript. A string can be traversed using: for loop or
while loop.
For Loop While Loop
A=‟Welcome‟ A=‟Welcome‟
for i in A: i=0
print (i ) while i<len(A):
print (A[i])
i+=1
1. Program to read a string and display in reverse order – display one character per line.
2. Program to read a string and display it in the form :
First character Last character
Last character First character
Like
T Y
R R
Y T
Printing
1. All Elements of String
2. Reverse order

str=input("enter a string")
length=len(str)
i=0
for a in range(-1,(-length-1),-1):
print(str[i],"\t",str[a])
i+=1

enter a stringtry
t y
r r
y t
STRING OPERATORS

String Concatenation Operator +


To concatenate, or combine, two strings you can use the + operator.
Example
Expression result
Merge variable a with variable b into variable c: ‘1’+’1’ ‘11’
a = "Hello" ‘A’+’0’ ‘A0’
b = "World" ‘123’+’ ‘+’abc’ ‘123 abc’
c=a+b
print(c)
a="hello”
HelloWorld
b="world"
To add a space between them, add a " ": print(a+' ‘+b) hello world
a = "Hello"
b = "World"
c=a+""+b
print(c)
Hello World
STRING OPERATORS

String Replication Operator *


Creates a new string that is a number of repetitions of the input string.
Expression Result
“abc” * 2 ‘abcabc’
5 * ”@” ‘@@@@@’
“3” * 2 ’33’
MEMBERSHIP OPERTORS

• There are two membership operators for strings.


• These are
• In – Returns True if character or substring exists in the given string, Otherwise False
• Not in - Returns True if character or substring does not exist in the given string,
Otherwise False
CHECK STRING
WITH IN KEYWORD

To check if a certain phrase or character is present in a string, we can use the keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
True
Use it in an if statement:
Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Yes, 'free' is present
CHECK IF NOT PRESENT WITH KEYWORD
NOT IN

To check if a certain phrase or character is NOT present in a string, we


can use the keyword not in.
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
True
COMPARISON OPERATORS

== This checks whether two strings are equal


!= This checks if two strings are not equal
< This checks if the string on its left is smaller than that on its right
<= This checks if the string on its left is smaller than or equal to that on its
right
> This checks if the string on its left is greater than that on its right
>= This checks if the string on its left is greater than or equal to that on its
right
String comparison in Python takes place character by character. That is, characters in
the same positions are compared from both the strings.
If the characters fulfill the given comparison condition, it moves to the characters in
the next position. Otherwise, it merely returns False.
Note: Some points to remember when using string comparison operators:
The comparisons are case-sensitive, hence same letters in different letter
cases(upper/lower) will be treated as separate characters
If two characters are different, then their Unicode value is compared; the character
with the smaller Unicode value is considered to be lower.
SLICING

You can return a range of characters by using the slice syntax.


Specify the start index and the end index, separated by a colon, to return a part
of the string. Example
Get the characters from position 2 to position 5 (not included):
b = "Hello" 0 1 2 3 4
print(b[2:5]) h e l l o
llo -5 -4 -3 -2 -1
Slice From the Start
By leaving out the start index, the range will start at the
first character: Example
Get the characters from the start to position 5 (not
included):
b = "Hello"
print(b[:5])
Hello
Slice To the End
By leaving out the end index, the range will go to the end:
Example
Get the characters from position 3, and all the way to the end:
b = "Hello, World!"
print(b[2:])
llo, World!

word="hello"
0 1 2 3 4 print(word [0:3]) hel
h e l l o print(word [1:]) ello
print(word [-4:-1]) ell
-5 -4 -3 -2 -1
print(word [:5]) hello
print(word[::-1]) olleh
#for printing reverse string
word="Hello"
print(word[::-1])
Note : string[::-1] is an easy method to reverse a string.

Write a program to input a string and check if it is a palindrome string using


string slice.

str=input("enter a string")
if(str==str[::-1]):
print(str, "is palindrome")
else:
print(str,"is not a palindrome")
STRING FUNCTIONS

Capitalize() – returns a string where the first character is upper case, and the rest is lower
case.
Syntax - [Link]()
Example:
if the first character is a
txt = "hello, welcome to my world." number:
x = [Link]() txt = "36 is my age."
print (x)
x = [Link]()
Output - Hello, welcome to my world. print (x)
Output - 36 is my age
txt = "python is FUN!"
x = [Link]()
print (x)
Output - Python is fun!
String functions and methods
• Functions can be used to manipulate strings and get new
values.

• A dot notation (".") is used to access these methods. Simply


type the string variable followed by a dot and then the method.

• Each method serves its own function. For example,


 .capitalize() capitalizes the first character in a string
 .count() counts the frequency of a specified substring within the
string, and
title() - returns a string where the first character in every word is
upper case. Like a header, or a title.
If the word contains a number or a symbol, the first letter after that will be
converted to upper case.
Syntax - [Link]()
Example:
txt = "Welcome to my 2nd world"
x = [Link]()
print(x)
Output - Welcome To My 2Nd World
txt = "hello b2b2b2 and 3g3g3g"
x = [Link]()
print(x)
Output - Hello B2B2B2 And 3G3G3G
lower() method returns a string where all characters are lower case.
Symbols and Numbers are ignored.
Syntax - [Link]()
Example :
txt = "Hello my FRIENDS"
x = [Link]()
print(x)
Output - hello my friends
upper() method returns a string where all characters are in upper case.
Symbols and Numbers are ignored.
Syntax - [Link]()
Example:
txt = "Hello my friends"
x = [Link]()
print(x)
Output - HELLO MY FRIENDS
count() - returns the number of times a specified value appears in the string.
Syntax - [Link](value, start, end)

value Required. A String. The string to value to search for


start Optional. An Integer. The position to start the search. Default is 0
end Optional. An Integer. The position to end the search. Default is the end of the string

Example:
txt = "I love apples, apple are my favorite fruit"
x = [Link]("apple")
print(x)
Output – 2
txt = "I love apples, apple are my favorite fruit"
x = [Link]("apple", 10, 24)
print(x)
Output - 1
find()- The find() method finds the first occurrence of the specified value.
The find() method returns -1(minus one) if the value is not found.
The find() method is almost the same as the index() method, the only difference is that
the index() method raises an exception if the value is not found.
Syntax - [Link](value, start, end)
Where in the text is the first occurrence of the letter "e"?:
txt = "Hello, welcome to my world."
x = [Link]("e")
print(x)
Output – 1
txt = "Hello, welcome to my world."
x = [Link]("e", 5, 10)
print(x)
Output - 8
index() - finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found.
Syntax - [Link](value, start, end)
txt = "Hello, welcome to my world."
x = [Link]("welcome")
print(x)
Output - 7
txt = "Hello, welcome to my world.”
print([Link]("q"))
print([Link]("q"))
Output - -1
Traceback (most recent call last):
File "demo_ref_string_find_vs_index.py", line 4 in <module>
print([Link]("q"))
ValueError: substring not found
startswith() - returns True if the string starts with the specified value, otherwise False.
Syntax - [Link](value, start, end)
Example:
#Check if the string starts with "Hello":
txt = "Hello, welcome to my world."
x = [Link]("Hello")
print(x)
Output – True

endswith() - returns True if the string ends with the specified value, otherwise False.
#Check if the string ends with a punctuation sign (.):
txt = "Hello, welcome to my world."
x = [Link](".") #Check if the string ends with the phrase "my world.":
print(x) txt = "Hello, welcome to my world."
x = [Link]("my world.")
Output – True print(x)
Output – True
isalnum() - returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
Example of characters that are not alphanumeric: (space)!#%&? etc.
Syntax - [Link]()
txt = "Company12” txt = "Company 12”
x = [Link]() x = [Link]()
print(x) print(x)
True False
isalpha() - returns True if all the characters are alphabet letters (a-z).

txt = "Company10"
x = [Link]()
print(x)
False
txt = "CompanyX"
x = [Link]()
print(x)
isdigit() - returns True if all the characters are digits, otherwise False.
Exponents, like ², are also considered to be a digit.
txt = "50800”
x = [Link]()
print(x)
True
islower()- returns True if all the characters are in lower case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.
a = "Hello world!"
b = "hello 123"
c = "mynameisPeter"
print([Link]())
print([Link]())
print([Link]())
False
True
False
isupper() - returns True if all the characters are in upper case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.

isspace() - Returns True if all characters in the string are whitespaces.


txt = " "
x = [Link]()
print(x)
True
lstrip() - removes any leading characters (space is the default leading character to remove)
txt = " banana "
x = [Link]()
print("of all fruits", x, "is my favorite")
of all fruits banana is my favorite
rstrip() - Returns a right trim version of the string. It removes any trailing characters (characters at the end a
string)
txt = " banana "
x = [Link]()
print("of all fruits", x, "is my favorite")
of all fruits banana is my favorite
strip() - Remove spaces at the beginning and at the end of the string:
txt = " banana "
x = [Link]()
print("of all fruits", x, "is my favorite")
of all fruits banana is my favorite

replace() - Returns a string where a specified value is replaced with a specified value.
txt = "one one was a race horse, two two was one too."
x = [Link]("one", "three")
print(x)
three three was a race horse, two two was three too.
join() - Joins a string or character after each member of the string iterator
>>> “*”.join(“Hello”)
‘H*e*l*lo’
>>>”***”,join(“TRIAL”)
‘T***R***I***A***L’
partition() - searches for a specified string, and splits the string into a tuple containing
three elements.
The first element contains the part before the specified string.
The second element contains the specified string.
The third element contains the part after the string.
txt = "I could eat bananas all day"
x = [Link]("bananas")
print(x)
('I could eat ', 'bananas', ' all day')
split() - Splits the string at the specified separator, and returns a list.
txt = "welcome to the jungle"
x = [Link]()
print(x)
['welcome', 'to', 'the', 'jungle']
Q1. Write a Python Program to Calculate the Number of Words and the Number of Characters
Present in a String.

Q 2. Write a program to input line of string from the user until enter is pressed. Count the total
number of uppercase letters, lowercase letters, alphabets, total number of digits, total number of
special symbols in the given text.

Q3 Write a program to check whether a substring is in the String or not. Print the place of
substring and number of times it is in the string.
Ans 1
my_string = "Hi there, how are you Will ? ”
my_chars=0
my_words=0
for i in my_string:
my_chars=my_chars+1
if(i==' '):
my_words=my_words+1
print("The number of words in the string are :”, my_words)
print("The number of characters in the string are :”, my_chars)
Ans 2.

string=input("enter a string")
lowerc=upperc=0
digitc=alphac=symbolc=0
for i in string: print("number of lowercase letters
if [Link](): :",lowerc)
print("number of uppercase letters
lowerc+=1 :",upperc)
elif [Link](): print("number of alphabets :",alphac)
upperc+=1 print("number of digits :",digitc)
print("number of symbols :",symbolc)
elif [Link]():
digitc+=1
elif [Link]():
alphac+=1
elif [Link]()!= True and i != ' ':
symbolc+=1
Ans3
string=input("enter a string")
subs=input("enter a substring")
for a in string:
c=[Link](subs)
p=[Link](subs)
print(subs,"is at",p,"place" )
print("number of times ",c)
Write a program to input line of string from the user until enter is pressed.
Count the
total number of character in the text(including spaces),
total number of alphabets,
total number of digits,
total number of special symbols and
total number of words in the given text.
line=input("enter a string")
alphac=charac=0
digitc=symbolc=0
wordc=1
print(”Number of characters are",charac)
for a in line:
print(" Number of alphabets are",alphac)
if [Link](): print(" Number of digits are",digitc)
print(" Number of symbols are",symbolc)
alphac+=1
print(" Number of words are",wordc)
elif [Link]():
digitc+=1
elif [Link]() != True and a != ' ':
symbolc+=1
elif a==' ':
wordc+=1
charac+=1

You might also like