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

PPS NOTES Unit-4.

Strings in Python represent a sequence of characters. Strings are immutable and indexed starting from 0. Individual characters in a string can be accessed using indexes or slices. Strings can be concatenated using the + operator and multiplied using the * operator. The in and not in operators check for membership in a string.

Uploaded by

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

PPS NOTES Unit-4.

Strings in Python represent a sequence of characters. Strings are immutable and indexed starting from 0. Individual characters in a string can be accessed using indexes or slices. Strings can be concatenated using the + operator and multiplied using the * operator. The in and not in operators check for membership in a string.

Uploaded by

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

Unit-IV(Strings)

Strings

A string is a data structure in Python that represents a sequence of characters. It is an immutable data type,
meaning that once you have created a string, you cannot change it. Python does not have a character data type, a
single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The
computer does not understand the characters; internally, it stores manipulated character as the combination of the
0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called
the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python
allows us to use single quotes, double quotes, or triple quotes to create the string.
Example in Python to create a string. 799

Syntax:
str = "Hi Python !"

Here, if we check the type of the variable str using a Python script Features of Java -

print(type(str)), then it will print a string (str). <class ‘str’>

Note:-In Python, strings are treated as the sequence of characters, which means that Python doesn't support the
character data-type; instead, a single character written as 'p' is treated as the string of length 1.
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides triple-
quotes to represent the string, but it is generally used for multiline string or docstrings.

#Using single quotes


str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)

#Using triple quotes


str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)

Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
--------------------------------------------*********************--------------------------------------------
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is
indexed as given in the below figure.

Consider the following example:

str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])

Output:
As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we
can use the : (colon) operator in Python to access the substring from the given string. Consider the following
example.

Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str = 'HELLO' is
given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
Consider the following example:

# Given String
str = "JAVATPOINT"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])

Output:
We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1. The
second rightmost index indicates -2, and so on. Consider the following image.

Consider the following example

str = 'JAVATPOINT'
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-12])

Output:
------------------------------------***********************---------------------------------------------
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support item
assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced.
Strings are immutable in Python.
Consider the following example.

Example 1
str = "HELLO"
str[0] = "h"
print(str)

Output:

However, in example 1, the string str can be assigned completely to a new content as specified in the following
example.
Example 2

str = "HELLO"
print(str)
str = "hello"
print(str)

Output:
-------------------------------------------*********************-----------------------------------------
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters from the string. But we can
delete the entire string using the del keyword.

str = "JAVATPOINT"
del str[1]

Output:

Now we are deleting entire string.

str1 = "JAVATPOINT"
del str1
print(str1)

Output:

----------------------------------------**********************---------------------------------------------

String Operators:-

Operator Description

+ It is known as concatenation operator used to join the strings given either side of
the operator.

* It is known as repetition operator. It concatenates the multiple copies of the same


string.

[] It is known as slice operator. It is used to access the sub-strings of a particular


string.

[:] It is known as range slice operator. It is used to access the characters from the
specified range.

in It is known as membership operator. It returns if a particular sub-string is present


in the specified string.

not in It is also a membership operator and does the exact reverse of in. It returns true if
a particular substring is not present in the specified string.

r/R It is used to specify the raw string. Raw strings are used in the cases where we
need to print the actual meaning of escape characters such as "C://python". To
define any string as a raw string, the character r or R is followed by the string.

% It is used to perform string formatting. It makes use of the format specifiers used
in C programming like %d or %f to map their values in python. We will discuss
how formatting is done in python.

Example
Consider the following example to understand the real use of Python operators.

str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello

Output:

Membership Operators
Membership operators are operators used to validate the membership of a value. It tests for membership in a
sequence, such as strings, lists, or tuples.
 in operator: The The in operator in Python can be used to check if a specific substring or character exists
within a larger string. Evaluate to true if it finds a variable in the specified sequence and false otherwise.
Example:
>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s in 'I saw The Holy Grail!'
False

# Python program to illustrate 'in' operator


string = "Hello, world!"
substring = "world"
if substring in string:
print("Found")
else:
print("Not Found")

#Output: Found: The substring 'world' was found in the string 'Hello, world!'.

#Example:
# Python program to illustrate 'in' operator
string = "Hello, world!"
char = "o"
if char in string:
print("Found")
else:
print("Not Found")
#Output: Found: The char 'o' was found in the string 'Hello, world!'.

‘not in’ operator- Evaluates to true if it does not finds a variable in specified sequence and false otherwise.
>>> s = 'spam'
>>> s not in 'I saw The Holy Grail!'
True
>>> s not in 'I saw spamalot!'
False

# Python program to illustrate 'in' operator


string = "Hello, world!"
substring = "world"
if substring not in string:
print("Found")
else:
print("Not Found")

#Output: Not Found: The substring 'world' was found in the string 'Hello, world!'.
#Example:
# Python program to illustrate 'in' operator
string = "Hello, world!"
char = "o"
if char not in string:
print("Found")
else:
print("Not Found")
#Output: Not Found: The char 'o' was found in the string 'Hello, world!'.
---------------------------------------****************************------------------------------------
Python String Formatting:-
Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given statement can be
written in single quotes or double quotes but it will raise the SyntaxError as it contains both single and double-
quotes.
Example
Consider the following example to understand the real use of Python operators.
str = "They said, "Hello what's going on?""
print(str)

Output:

We can use the triple quotes to accomplish this problem but Python provides the escape sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special character and it
interpreted differently. The single quotes inside the string must be escaped. We can apply the same as in the
double quotes.
Example -

# using triple quotes


print('''''They said, "What's there?"''')

# escaping single quotes


print('They said, "What\'s going on?"')

# escaping double quotes


print("They said, \"What's going on?\"")

Output:

The list of an escape sequence is given below:

Sr. Escape Description Example


Sequence

1. \newline It ignores the new print("Python1 \


line. Python2 \
Python3")
Output:
Python1 Python2 Python3

2. \\ Backslash print("\\")
Output:
\

3. \' Single Quotes print('\'')


Output:
'

4. \\'' Double Quotes print("\"")


Output:
"

5. \a ASCII Bell print("\a")

6. \b ASCII Backspace(BS) print("Hello \b World")


Output:
Hello World

7. \f ASCII Formfeed print("Hello \f World!")


Hello World!

8. \n ASCII Linefeed print("Hello \n World!")


Output:
Hello
World!

9. \r ASCII Carriege print("Hello \r World!")


Return(CR) Output:
World!

10. \t ASCII Horizontal Tab print("Hello \t World!")


Output:
Hello World!

11. \v ASCII Vertical Tab print("Hello \v World!")


Output:
Hello
World!

12. \ooo Character with octal print("\110\145\154\154\157")


value Output:
Hello

13 \xHH Character with hex print("\x48\x65\x6c\x6c\x6f")


value. Output:
Hello

Here is the simple example of escape sequence.

print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
print("This is the \n multiline quotes")
print("This is \x48\x45\x58 representation")

Output:
We can ignore the escape sequence from the given string by using the raw string. We can do this by
writing r or R in front of the string. Consider the following example.

print(r"C:\\Users\\DEVANSH SHARMA\\Python32")

Output:

-----------------------------------------------*******************----------------------------------------

The format() method:-


The format() method is the most flexible and useful method in formatting strings. The curly braces {} are used as
the placeholder in the string and replaced by the format() method argument. Let's have a look at the given an
example:

# Using Curly braces


print("{} and {} both are the best friend".format("Devansh","Abhish
ek"))

#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))

#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))

Output:

Python String Formatting Using % Operator:-


Python allows us to use the format specifiers used in C's printf statement. The format specifiers in Python are
treated in the same way as they are treated in C. However, Python provides an additional operator %, which is
used as an interface between the format specifiers and their values. In other words, we can say that it binds the
format specifiers to the values.
Consider the following example.
Integer = 10;
Float = 1.290
String = "Devansh"
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ... My value
is %s"%(Integer,Float,String))

Output:

Formatted String using F-strings


To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same
way that you would with str.format(). F-strings provide a concise and convenient way to embed python
expressions inside string literals for formatting.
Example: Formatting string with F-Strings
name = 'Ashutosh'
print(f"My name is {name}.")
Output:

My name is Ashutosh.

This new formatting syntax is very powerful and easy. You can also insert arbitrary Python expressions and
you can even do arithmetic operations in it.
Example: Arithmetic operations using F-strings
a = 5
b = 10
print(f"He said his age is {2 * (a
+ b)}.")

Output:
He said his age is 30.

We can also use lambda expressions in f-string formatting. Example: Lambda Expressions using F-strings

--------------------------------------------*************************-----------------------------------------

Python built in String functions:-


Python provides various in-built functions that are used for string handling. Many String fun

Method Description

capitalize() It capitalizes the first character of the String. This


function is deprecated in python3
casefold() It returns a version of s suitable for case-less
comparisons.

center(width ,fillchar) It returns a space padded string with the original string
centred with equal number of left and right spaces.

count(string,begin,end) It counts the number of occurrences of a substring in a


String between begin and end index.

decode(encoding = 'UTF8', errors Decodes the string using codec registered for encoding.
= 'strict')

encode() Encode S using the codec registered for encoding.


Default encoding is 'utf-8'.

endswith(suffix It returns a Boolean value if the string terminates with


,begin=0,end=len(string)) given suffix between begin and end.

expandtabs(tabsize = 8) It defines tabs in string to multiple spaces. The default


space value is 8.

find(substring ,beginIndex, It returns the index value of the string where substring is
endIndex) found between begin index and end index.

format(value) It returns a formatted version of S, using the passed


value.

index(subsring, beginIndex, It throws an exception if string is not found. It works


endIndex) same as find() method.

isalnum() It returns true if the characters in the string are


alphanumeric i.e., alphabets or numbers and there is at
least 1 character. Otherwise, it returns false.

isalpha() It returns true if all the characters are alphabets and there
is at least one character, otherwise False.

isdecimal() It returns true if all the characters of the string are


decimals.

isdigit() It returns true if all the characters are digits and there is
at least one character, otherwise False.

isidentifier() It returns true if the string is the valid identifier.

islower() It returns true if the characters of a string are in lower


case, otherwise false.

isnumeric() It returns true if the string contains only numeric


characters.

isprintable() It returns true if all the characters of s are printable or s


is empty, false otherwise.

isupper() It returns false if characters of a string are in Upper case,


otherwise False.

isspace() It returns true if the characters of a string are white-


space, otherwise false.

istitle() It returns true if the string is titled properly and false


otherwise. A title string is the one in which the first
character is upper-case whereas the other characters are
lower-case.

isupper() It returns true if all the characters of the string(if exists)


is true otherwise it returns false.

join(seq) It merges the strings representation of the given


sequence.

len(string) It returns the length of a string.

ljust(width[,fillchar]) It returns the space padded strings with the original


string left justified to the given width.

lower() It converts all the characters of a string to Lower case.

lstrip() It removes all leading whitespaces of a string and can


also be used to remove particular character from leading.

partition() It searches for the separator sep in S, and returns the part
before it, the separator itself, and the part after it. If the
separator is not found, return S and two empty strings.

maketrans() It returns a translation table to be used in translate


function.

replace(old,new[,count]) It replaces the old sequence of characters with the new


sequence. The max characters are replaced if max is
given.

rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the string in backward


direction.

rindex(str,beg=0,end=len(str)) It is same as index but it traverses the string in backward


direction.
rjust(width,[,fillchar]) Returns a space padded string having original string
right justified to the number of characters specified.

rstrip() It removes all trailing whitespace of a string and can


also be used to remove particular character from trailing.

rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from the
backward direction. It returns the list of words in the
string. If Separator is not specified then the string splits
according to the white-space.

split(str,num=string.count(str)) Splits the string according to the delimiter str. The string
splits according to the space if the delimiter is not
provided. It returns the list of substring concatenated
with the delimiter.

splitlines(num=string.count('\n')) It returns the list of strings at each line with newline


removed.

startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string starts with given


str between begin and end.

strip([chars]) It is used to perform lstrip() and rstrip() on the string.

swapcase() It inverts case of all characters in a string.

title() It is used to convert the string into the title-case i.e., The
string meEruT will be converted to Meerut.

translate(table,deletechars = '') It translates the string according to the translation table


passed in the function .

upper() It converts all the characters of a string to Upper Case.

zfill(width) Returns original string leftpadded with zeros to a total of


width characters; intended for numbers, zfill() retains
any sign given (less one zero).

rpartition()
---------------------------------------*************-----------------------------------------------------

Strings Concatenations:-
Python string is a collection of Unicode characters. Python provides many built-in functions for string
manipulation. String concatenation is a process when one string is merged with another string. It can be done in
the following ways.
 Using + operators
 Using join() method
 Using % method
 Using format() function
Let's understand the following string concatenation methods.
Using + operator
This is an easy way to combine the two strings. The + operator adds the multiple strings together. Strings must be
assigned to the different variables because strings are immutable. Let's understand the following example.
Example -

# Python program to show string concatenation

# Defining strings
str1 = "Hello "
str2 = "Python"

# + Operator is used to strings concatenation


str3 = str1 + str2
print(str3) # Printing the new combined string

Output:
Hello Python
Explanation:
In the above example, the variable str1 stores the string "Hello", and variable str2 stores the "Devansh". We used
the + operator to combine these two string variables and stored in str3.
Using join() method
The join() method is used to join the string in which the str separator has joined the sequence elements. Let's
understand the following example.
words = ["hello", "world"]
delimiter = " "
sentence = delimiter.join(words)
print(sentence)
Example -

# Python program to string concatenation

str1 = "Hello "


str2 = "Kaustubh Tripathi"

# join() method is used to combine the strings


print("".join([str1, str2]))

# join() method is used to combine


# the string with a separator Space(" ")
str3 = " ".join([str1, str2])

print(str3)
Output:
Hello Kaustubh Tripathi
Hello Kaustubh Tripathi

Explanation:
In the above code, the variable str1 stores the string "Hello" and variable str2 stores the " Kaustubh Tripathi".
The join() method returns the combined string that is stored in the str1 and str2. The join() method takes only list
as an argument.
Using % Operator
The % operator is used for string formatting. It can also be used for string concatenation. Let's understand the
following example.
Example -
# Python program to demonstrate
# string concatenation

str1 = "Hello"
str2 = "Kaustubh"

# % Operator is used here to combine the string


print("% s % s" % (str1, str2))
Output

Hello Kaustubh

Explanation -
In the above code, the %s represents the string data-type. We passed both variables's value to the %s that
combined the strings and returned the "Hello Kaustubh".
Using format() function:-
Python provides the str.format() function, which allows use of multiple substitutions and value formatting. It
accepts the positional arguments and concatenates the string through positional formatting. Let's understand the
following example.
Example -

# Python program to show


# string concatenation

str1 = "Hello"
str2 = "ISBM"

# format function is used here to


# concatenate the string
print("{} {}".format(str1, str2))

# store the result in another variable


str3 = "{} {}".format(str1, str2)
print(str3)
Output

Explanation:
In the above code, the format() function combines both strings and stores into the str3 variable. The curly braces
{} are used as the position of the strings.
-----------------------------------------------**********************----------------------------------------

Appending of Strings:-

As we know, the object of the string is immutable when we use the “+” operator for concatenating strings, a new
different string is created. Whereas the appending of the string is just to modify the original string, which is also
similar to using the “+” operator. This append function is mostly used on a list of strings. To repeatedly append
the strings, we need to first convert it into a list, then append the given elements to that list, and then join the list
back to the appended string.
Now let us see how to append a string using the “+” operator, which is also known as a concatenation of strings.
Let us see the below example, which uses the “+” operator for concatenating the given string.
Example:
str1 = "ISBM, PUNE"
str2 = " COE, PGDM"
print("The given original string : " + str(str1))
print("The string given to append to the previous string: " +
str(str2))
res = str1 + str2
print("The Modified string is obtained as follows:")
print(res)

Output

In the above program, we have seen that there are two strings, “str1” and “str2,” where str1 is appended with str2
using the “ +“ operator. This is done in the statement “res = str1 + str2,” where we are adding string 1to strin2 to
obtain the result, which is stored in the variable “res.” The result is the addition of two strings, or we can say str2
is appended to str1. We can see str2 starts with white space so that when it is appended to the str1, we can read it
properly.
Now let us see how to use the append() function to append two strings. This function also works similarly to the
“+” operator as above. Let us see the below example using the append() function. This function is mainly used to
append more than two strings.
Syntax:
str.append(items)

Where item which is to be added to the list of strings. This will add a single item to the given string or list of
strings.
Example:
str1 = ['ISBM', 'COE', 'PUNE']
print("The first string list is given as follows:")
print(str1)
str2 = ['MAHARASTRA', 'INDIA']
print("The second string list that needs to be appneded to the first string list is as follows")
print(str2)
str1.append(str2)
print("The modified string list after appending is as follows:")
print(str1)

Output

In the above program, we can see we have two string lists where str2 needs to be appended to the str1, and the
result is obtained with one single string having the second string appended to it.
--------------------------------------********************---------------------------------------------------

Multiplication(*) operator with String


Multiplication operator is used with strings in Python for the purpose of repetition. Multiplication operator when
used with string in Python creates new strings by concatenating multiple copies of the same string.

print('Hello' * 5)
Output

HelloHelloHelloHelloHello

String Slicing in Python


Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end.
Python slicing can be done in two ways.
 slice() Constructor
 Extending Indexing
slice() Constructor:
The slice() constructor creates a slice object representing the set of indices specified by range(start, stop, step).
Syntax:
 slice(stop)
 slice(start, stop, step)
Parameters:
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each index for slicing.
Return Type: Returns a sliced object containing elements in the given range only.
# Python program to demonstrate
# string slicing

# String slicing
String ='ASTRING'

# Using slice constructor


s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)

print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Output:

Extending indexing
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and convenient way
to slice a string both syntax wise and execution wise.
Syntax
string[start:end:step]

Note:- start, end and step have the same mechanism as slice() constructor.
Example # Python program to demonstrate

# string slicing

# String slicing
String ='ASTRING'
# Using indexing sequence
print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2])

# Prints string in reverse


print("\nReverse String")
print(String[::-1])

Output:

-----------------------------------------------***********************-----------------------------------------------

ord() function in Python:-


Python ord() function returns the Unicode from a given character. This function accepts a string of unit
length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a
string of length 1, the ord() function returns an integer representing the Unicode code point of the character
when an argument is a Unicode object, or the value of the byte when the argument is an 8-bit string.
Syntax:

ord(character)
Note: If the string length is more than one, and a TypeError will be raised. The syntax can be ord(“a”) or
ord(‘a’), both will give same results.
Example
# inbuilt function return an
# integer representing the Unicode code
value = ord("A")

# writing in ' ' gives the same result


value1 = ord('A')

# prints the unicode value


print (value, value1)
Output:
65 65

Example : Python ord() Error Condition


A TypeError is raised when the length of the string is not equal to 1 as shown below:
# inbuilt function return an
# integer representing the
Unicode code
# demonstrating exception

# Raises Exception
value1 = ord('AB')

# prints the unicode value


print(value1)
Output:

Traceback (most recent call last):


File “/home/f988dfe667cdc9a8e5658464c87ccd18.py”, line 6, in
value1 = ord(‘AB’)
TypeError: ord() expected a character, but string of length 2 found

chr() functions:
The chr() method returns a string representing a character whose Unicode code point is an integer.
Syntax: chr(num)
num : integer value

Note:-Where ord() methods work on opposite for chr() function:


Example of ord() and chr() functions

# inbuilt function return an


# integer representing the Unicode code
value = ord("A")

# prints the unicode value


print (value)

# print the character


print(chr(value))

Output:
65
A
---------------------------------------****************************------------------------------------------
in and not in operators:
The in operator can be used to check if a substring is present within a string. For example:
# use of in membership operator

string = "Hello, Ashutosh!"


substring = " Ashutosh "
if substring in string:
print("Substring found in string.")

Output:
Substring found in string.
# use of not in membership operator

string = "Hello, Ashutosh !"


substring = "Ram"
if substring not in string:
print("Substring not in string.")
Output:
Substring not in string.
-------------------------------------*************************-------------------------------------------------
String Comparison:-
To compare two strings, we mean that we want to identify whether the two strings are equivalent to each other or
not, or perhaps which string should be greater or smaller than the other.
This is done using the following 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
How to execute the comparison
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.
Methods of String Comparision:-
Method 1: Using Relational Operators-
The relational operators compare the Unicode values of the characters of the strings from the zeroth index till
the end of the string. It then returns a boolean value according to the operator used.
print("Hello" == "Hello")
print("Hello" < "Hello")
print("Hello" > "Hell")
print("Hello" > "hello")
print("Hello" < "hello")
print("Hello" != "Hello")
Output:
True
False
True
False
True
False
Method 2: Using is and is not
The == operator compares the values of both the operands and checks for value equality. Whereas is operator
checks whether both the operands refer to the same object or not. The same is the case for != and is not.
Let us understand this with an example:
str1 = "Hello"
str2 = "Hello"
str3 = str1

print("ID of str1 =", hex(id(str1)))


print("ID of str2 =", hex(id(str2)))
print("ID of str3 =", hex(id(str3)))
print(str1 is str1)
print(str1 is str2)
print(str1 is str3)

str1 += "o"
str4 = "Hello"

print("\nID of changed str1 =", hex(id(str1)))


print("ID of str4 =", hex(id(str4)))
print(str1 is str4)

Output:
ID of str1 = 0x7f1b492481b0
ID of str2 = 0x7f1b492481b0
ID of str3 = 0x7f1b492481b0
True
True
True

ID of changed str1 = 0x7f1b4910d030


ID of str4 = 0x7f1b492481b0
False
Method 3: Creating a user-defined function.
By using relational operators we can only compare the strings by their unicodes. In order to compare two
strings according to some other parameters, we can make user-defined functions.
In the following code, our user-defined function will compare the strings based upon the number of digits.
# function to compare string based on the number
of digits
def compare_strings(str1, str2):
count1 = 0
count2 = 0

for i in range(len(str1)):
if str1[i] >= "0" and str1[i] <= "9":
count1 += 1

for i in range(len(str2)):
if str2[i] >= "0" and str2[i] <= "9":
count2 += 1

return count1 == count2

print(compare_strings("123", "12345"))
print(compare_strings("12345", "hello"))
print(compare_strings("12hello", "hello12"))
Output:
False
False
True
--------------------------------------------***************------------------------------------------

Iterate over characters of a string in Python


In Python, while operating with String, one can do multiple operations on it. Let’s see how to iterate over
characters of a string in Python.
Example #1: Using simple iteration and range()
# Python program to iterate over characters of a string

string_name = "Shreeram Tripathi"

# Iterate over the string


for element in string_name:
print(element, end=' ')
print("\n")

# Code #2
string_name = "Shreeram"

# Iterate over index


for element in range(0, len(string_name)):
print(string_name[element])
Output:

Shreeram Tripathi

S
h
r
e
e
r
a
m
Example #2: Using enumerate() function: the string is an array, and hence you can loop over it. If you pass a
string to enumerate(), the output will show you the index and value for each character of the string .
# Python program to iterate over characters of a
string

string_name = "Shreeram"

# Iterate over the string


for i, v in enumerate(string_name):
print(v)

Output:
S
h
r
e
e
r
a
m
Example #3: Iterate characters in reverse order
# Python program to iterate over characters of a string
# Code #1
string_name = "SHREERAM"
# slicing the string in reverse fashion
for element in string_name[ : :-1]:
print(element, end =' ')
print('\n')

# Code #2
string_name = "SHREERAM TRIPATHI"

# Getting length of string


ran = len(string_name)

# using reversed() function


for element in reversed(range(0, ran)):
print(string_name[element])
Output:
MAREERHS

I
H
T
A
P
I
R
T

M
A
R
E
E
R
H
S
Example #4: Iteration over particular set of element.
# Python program to iterate over particular set
of element.

string_name ="Shreeram Tripathi"

# string_name[start:end:step]
for element in string_name[0:8:1]:
print(element,end =' ')
Output:
S h r e e r a m
----------------------------------------**************************--------------------------------------
String module:
The string module in Python is a built-in module that provides a collection of useful string
operations and constants.
Some of the commonly used functions and constants in the string module include:
 string.ascii_letters: A string containing all letters (both uppercase and lowercase) in the
ASCII character set.
 string.ascii_lowercase: A string containing all lowercase letters in the ASCII character set.
 string.ascii_uppercase: A string containing all uppercase letters in the ASCII character set.
 string.digits: A string containing all digits (0-9) in the ASCII character set.
 string.hexdigits: A string containing all hexadecimal digits (0-9 and A-F) in the ASCII
character set.
 string.octdigits: A string containing all octal digits (0-7) in the ASCII character set.
 string.punctuation: A string containing all punctuation characters in the ASCII character
set.
 string.whitespace: A string containing all whitespace characters in the ASCII character set.
 string.capwords(s): Capitalize the first letter of each word in a string.
 string.maketrans(x[, y[, z]]): Returns a translation table usable for str.translate().
 string.Template(template): A class for creating simple templates.

Reference: https://docs.python.org/3/library/string.html
----------------------------------------**************************--------------------------------------

String Programs:

Program: Calculate the length of string without using inbuilt function.

def string_length(string):
count = 0
for char in string:
count += 1
return count
or
string=raw_input("Enter string:")
count=0
for i in string:
count=count+1
print("Length of the string is:")
print(count)

Program: String reversal without using inbuilt function


def string_reverse(string):
string_list = list(string)
string_list = string_list[::-1]
reversed_string = ''.join(string_list)
return reversed_string
or
def string_reverse(string):
string_list = list(string)
start = 0
end = len(string_list) - 1
while start < end:
string_list[start],string_list[end] = string_list[end],string_list[start]
start += 1
end -= 1
return ''.join(string_list)

Program: Equality check of two strings without using inbuilt function


def string_equal(string1, string2):
if len(string1) != len(string2):
return False
else:
for i in range(len(string1)):
if string1[i] != string2[i]:
return False
return True
or
def string_equal(string1, string2):
i=0
while i < len(string1) and i < len(string2):
if string1[i] != string2[i]:
return False
i += 1
return True
Program:Check palindrome without using inbuilt function
def is_palindrome(string):
start = 0
end = len(string) - 1
while start < end:
if string[start] != string[end]:
return False
start += 1
end -= 1
return True
or
string=raw_input("Enter string:")
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("The string isn't a palindrome")

Program: Check substring without using inbuilt function


def is_substring(string, substring):
n = len(string)
m = len(substring)
for i in range(n - m + 1):
j=0
while j < m:
if string[i + j] != substring[j]:
break
j += 1
if j == m:
return True
return False

Program : Count Number of Lowercase Characters in a String

string=raw_input("Enter string:")
count=0
for i in string:
if(i.islower()): #isupper() for comparing upper case
count=count+1
print("The number of lowercase characters is:")
print(count)

Program: Count the Number of Words and Characters in a String

string=raw_input("Enter string:")
char=0
word=1
for i in string:
char=char+1
if(i==' '):
word=word+1
print("Number of words in the string:")
print(word)
print("Number of characters in the string:")
print(char)

Program: Replace Every Blank Space with Hyphen in a String


string=raw_input("Enter string:")
string=string.replace(' ','-')
print("Modified string:")
print(string)

Program t: Count Number of Uppercase and Lowercase Letters in a String

string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if(i.islower()):
count1=count1+1
elif(i.isupper()):
count2=count2+1
print("The number of lowercase characters is:")
print(count1)
print("The number of uppercase characters is:")
print(count2)

Program: Count the Number of Vowels in a String


string=raw_input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)

Program : Remove the nth Index Character from a Non-Empty String

def remove(string, n):


first = string[:n]
last = string[n+1:]
return first + last
string=raw_input("Enter the sring:")
n=int(input("Enter the index of the character to remove:"))
print("Modified string:")
print(remove(string, n))

Program : Remove Odd Indexed Characters in a string


def modify(string):
final = ""
for i in range(len(string)):
if i % 2 == 0:
final = final + string[i]
return final
string=raw_input("Enter string:")
print("Modified string is:")
print(modify(string))

Program : Replace All Occurrences of ‘a’ with $ in a String


string=input("Enter string:")
string=string.replace('a','$')
string=string.replace('A','$')
print("Modified string:")
print(string)

Program : Count the Number of Digits and Letters in a String

string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)

Program :Print All Letters Present in Both Strings


s1=raw_input("Enter first string:")
s2=raw_input("Enter second string:")
a=list(set(s1)|set(s2))
print("The letters are:")
for i in a:
print(i)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy