String in Python
String in Python
String in Python
Understanding the concept of strings
1
2025-11-02
2
2025-11-02
Yo uTube Website
Quote
3
2025-11-02
This content covers the topics from these books and more..
4
2025-11-02
What is a String
A string is a sequence of characters — which can include letters, digits, symbols, spaces, or special
characters — enclosed in single (' ') quotes , double (" ") quotes or triple (''' ''') quotes. Strings can be
single-line or multi-line, depending on how they are written.
5
2025-11-02
Formatting of a String
name = "Rohit"
subject = "CS"
print("Mr {} teaches {} ".format(name,subject))
Mr Rohit teaches CS
Go Slow, doubling the speed will not double the speed of understanding [Link]
Traversing a string
Traversing a string means accessing each character of the string one by one, typically using a loop, to
perform operations such as searching, counting, or displaying characters. Traversing is like walking through
each letter of the string — step by step, from start to end — to examine or process it.
msg="superb" msg="Python" P
for i in msg: l=len(str) y
print(i,"-",end=' ') i=0 t
s -u -p -e -r -b while i<l: h
print(msg[i]) o
i+=1 n
6
2025-11-02
Write a program to count the number of "p" in "pineapple". (including capital and small letters)
7
2025-11-02
Write a program to count the number of "p" and "a" separately after getting the value from the user.
Write a program to count the number of occurrences of a given character entered by the user.
8
2025-11-02
Write a program to count the number of vowels and consonants after getting the value from the user.
Write a program to count the number of times a character occurs and display its position too.
9
2025-11-02
Write a program to read a string from the user and display each character along with its position (index).
10
2025-11-02
Updation in String
It is an immutable datatype, which means that the content of the string cannot be changed. It will internally
create a new string rather than modify the old string in place. A string is accessed using a subscript (index).
Example Think of a string like a necklace of beads. Each bead (character) has
s='anata won'
its fixed place on the thread — you can count or copy them, but
s[3]='y'
you can’t just replace one bead without making a new necklace.
print(s)
TypeError That’s why strings in Python are immutable.
Go Slow, doubling the speed will not double the speed of understanding [Link]
11
2025-11-02
Concatenation
It refers to the process of joining two or more strings together to form a single new string. This is achieved
using the + operator, which combines the contents of the strings in the same order as they are written.
Replication
Replication means repeating a string multiple times to form a new string. In Python, this is done using the *
(asterisk) operator, which multiplies the string by a number (integer) — creating repeated copies of it.
12
2025-11-02
Membership operators
Membership operators are used to check whether a character or a substring exists within another string. Python
provides two membership operators — “in” and “not in” — to perform this check.
❑ in: returns True if the character or substring exists in the given string.
❑ not in: returns True if the character or substring does not exist in the given string
Comparison operators
In Python, strings can be compared using relational comparison operators such as <, >, <=, >=, ==, and !=.
Python compares strings lexicographically, meaning it compares the ASCII values of characters one by one
from left to right. 0 to 9 = 48-57 , A and Z = 65-90 , a and z = 97-122
13
2025-11-02
Comparison operators
Comparison operators
'a'<"A" "Goodbye" < "Hello"
False True
14
2025-11-02
Accessing Elements
We need to use an index that allows us to access an element of a list using either positive or negative
values. Slicing can also be done using an index in the form of [start, stop, step] to access the elements.
word='Hello world'
Indexing
15
2025-11-02
Write a program that accepts n times from the user and repeats 'GOOD MORNING' n number of times.
16
2025-11-02
Write a program to ask the first, last and middle name of the user, then print the value in concatenation.
Go Slow, doubling the speed will not double the speed of understanding [Link]
Write a program that takes a string input and prints the characters at even indices only.
17
2025-11-02
Write a program that takes a string from the user and displays it in reverse without using loops.
18
2025-11-02
19
2025-11-02
Yo uTube Website
20
2025-11-02
The lower() method in Python is used to convert all The upper() method in Python is used to convert all
uppercase letters in a string to lowercase. Other lowercase letters in a string to uppercase. Other
characters (like digits, spaces, and symbols) remain characters (digits, spaces, symbols) remain unchanged.
unchanged.
Example Example
str='WELcome' str='WELcome'
print([Link]()) print([Link]())
welcome WELCOME
21
2025-11-02
The capitalize() method in Python returns a new string The title() method returns a new string where the first
where the first character is converted to uppercase, and character of each word is capitalized, and all other
all other characters are converted to lowercase. characters are converted to lowercase.
Example Example
text = "python is powerful" text = "welcome to python programming"
line = [Link]() print([Link]())
print(line) Welcome To Python Programming
Python is powerful
Go Slow, doubling the speed will not double the speed of understanding [Link]
The title() method returns a new string where the first The swapcase() returns a new string where all uppercase
character of each word is capitalised, and all other letters are converted to lowercase, and all lowercase
characters are converted to lowercase. letters are converted to uppercase. Other characters,
such as digits, symbols, or spaces, remain unchanged.
Example Example
text = "welcome to python programming" text = "pyTHon"
line = [Link]() line = [Link]()
print(line) print(line)
Welcome To Python Programming PYthON
Go Slow, doubling the speed will not double the speed of understanding [Link]
22
2025-11-02
text = "WELcome"
print([Link]())
print([Link]())
Write a program to accept a word from the user and count the number of upper and lower case.
23
2025-11-02
24
2025-11-02
The len() function in Python is used to find the total number of characters in a string. This count includes
letters, digits, symbols, spaces, and special characters. If the length is 0, it is called an Empty String
Example Example
c='SinghClasses' text = "Python is fun!"
print(len(c)) print(len(text))
12 14
The index() method returns the position (index) of the first occurrence of a specified substring within the
given string. If the substring is not found, it raises a ValueError. Syntax: [Link](substring, start, end)
Example Example
text = "Welcome to Python" text = "banana"
pos = [Link]("Python") pos = [Link]("a", 2, 5)
print(pos) print(pos)
11 3
25
2025-11-02
The count() method returns the number of occurrences of a specified substring within a given string. It can also
be used to count occurrences within a specific range of indices using optional start and end parameters.
Example Example
text = "banana" text = "banana"
val=[Link]("a") val=[Link]("a",2,5)
print(val) print(val)
3 1
The find() method in Python is used to search for a substring within a string and return the index (position)
of its first occurrence. If the substring is not found, it returns -1 instead of causing an error.
Example Example
str="jhony jhony yes papa" str="jhony jhony yes papa"
pos=[Link]('yes') pos=[Link]('jhony')
print(pos) print(pos)
12 0
26
2025-11-02
Example
str="jhony jhony yes papa"
pos=[Link]('jhony',2,3)
print(pos)
-1
The replace() method is used to replace a specified substring with another substring in a string. It creates a
new string with the replacements; the original string remains unchanged.
Example Example
str= "Honesty is the best policy" str='This is an example'
str=[Link](" ","-") print([Link]('is','was'))
print(str) Thwas was an example
27
2025-11-02
Write a program to replace all the words 'do' with 'done' in the following string: "I do you do and we all will do"
Go Slow, doubling the speed will not double the speed of understanding [Link]
28
2025-11-02
29
2025-11-02
The strip() method in Python is used to remove unwanted spaces or specified characters from both the
beginning and the end of a string. It’s often used to clean user input or text data.
Example Example
text = " Hello Python! " word = "***Welcome***"
str=[Link]() str=[Link]('*')
print(str) print(str)
Hello Python! [Link]('*')
The lstrip() method removes spaces or specified characters only from the left side (beginning) of a string.
Example Example
text = " Hello Python! " word = "###Python###"
str=[Link]() str=[Link]('#')
print(str) print(str)
Hello Python! Python###
30
2025-11-02
The rstrip() method removes spaces or specified characters only from the right side (ending) of a string.
Example Example
text = " Hello Python! " word = "***Welcome***"
str=[Link]() str=[Link]('*')
print(str) print(str)
Hello Python! ***Welcome
The replace() method is used to replace a specified substring with another substring in a string. It creates a
new string with the replacements; the original string remains unchanged.
Example Example
str= "Honesty is the best policy" str='This is an example'
str=[Link](" ","-") print([Link]('is','was'))
print(str) Thwas was an example
31
2025-11-02
The split() method divides a string into a list of substrings, based on a specified separator (delimiter). If no
separator is provided, it uses whitespace (space, tab, newline) by default.
Syntax: [Link](separator, maxsplit)
Example Example
text = "Python is powerful" line = "one two three four"
words = [Link]() words = [Link](' ', 2)
print(words) print(words)
['Python', 'is', 'powerful'] ['one', 'two', 'three four']
The partition() method searches for a specified separator in the string. It returns a tuple containing these
three elements and divides the string into three parts: The part before the separator, the separator itself,
and the part after the separator.
Example Example
text = "Python is powerful" msg = "Learning never ends"
print([Link]("is")) print([Link]("AI"))
('Python ', 'is', ' powerful') ('Learning never ends', '', '')
32
2025-11-02
Write a program to input a line of text from the user and print the longest word in the line.
33
2025-11-02
Write a program that replaces all vowels in the string with “*” entered by the user.
Write a program to accept a string and display each word and its length.
34
2025-11-02
Write a program to input a string, then count and display the occurrences of words starting with I and E.
Write a program to input a string, then count and display the occurrences of words starting with a vowel.
35
2025-11-02
The join() method combines the elements of an iterable (like a list, tuple, or string) into a single string,
inserting the calling string as a separator between each element. Syntax [Link](iterable)
Example Example
numbers = ('1', '2', '3', '4') items = ['apple', 'banana', 'cherry']
print('-'.join(numbers)) print(', '.join(items))
1-2-3-4 apple, banana, cherry
The startswith() method checks whether a string starts with a specified prefix (substring). It returns True if
the string begins with the given substring; otherwise, False. Syntax [Link](substr,start, end)
Example Example
text = "Python Programming" msg = "welcome to python"
print([Link]("Py")) print([Link]("come", 3, 8))
True True
36
2025-11-02
The endswith() method checks whether a string ends with a specified suffix (substring). It returns True if
the string ends with that substring; otherwise, False. Syntax [Link](substring, start, end)
Example Example
quote = "Learning is continuous" msg = "Hello Python"
print([Link]("continuous")) print([Link]("on", 4, 12))
True True
The ord() function returns the Unicode (ASCII) integer value of a given character. Syntax: ord(character)
The chr() function does the reverse of ord(). It returns the character that corresponds to a given Unicode
(ASCII) integer. Syntax chr(integer)
Example Example
print(ord('A')) print(chr(65))
print(ord('a')) print(chr(97))
print(ord(' ')) print(chr(36))
65 A
97 a
32 $
© 2025 Rohit Singh. All rights reserved.
37
2025-11-02
38
2025-11-02
Consider the string str=”Global Warming” Write the appropriate statement for the following
Write statements to implement the following ❑ To trim the characters from the string.
❑ To display the last four characters. ❑ Count the number of characters in the string
❑ To display a string starting from 4 to 8. ❑ Change the first character to a capital letter
❑ To change the case of the given string. ❑ To change a lowercase letter to an uppercase letter
❑ To check if the string is in title case. ❑ Check whether the given character is a letter.
❑ To replace all the occurrences 'a' with '*’ ❑ Replace all the occurrences of the old string with the
❑ To check whether a string is alphanumeric or not. new string.
❑ To display the starting index for the substring „Wa‟.
Go Slow, doubling the speed will not double the speed of understanding [Link]
39
2025-11-02
The isalnum() method checks whether all characters in a string are alphanumeric, i.e., letters (A–Z, a–z) and numbers
(0–9). It returns:
True → if every character is a letter or digit and the string is not empty.
40
2025-11-02
The isalpha() method in Python is used to check whether all characters in a string are alphabetic letters (A–Z, a–z). It
returns True if the string contains only letters and is not empty; otherwise, it returns False. This is useful when
validating names, words, or any input that should contain letters only, without digits, spaces, or special characters.
The isdigit() method in Python is used to check whether all characters in a string are numeric digits (0–9). It
returns True if the string contains only digits and is not empty; otherwise, it returns False. This is
particularly useful when validating numbers, IDs, PINs, or any input that should consist solely of digits.
41
2025-11-02
The islower() method in Python checks whether all alphabetic characters in a string are in lowercase (a–z).
It returns True if all letters are lowercase and there is at least one alphabetic character; otherwise, it returns
False. This method is useful when validating text input that requires lowercase letters.
Go Slow, doubling the speed will not double the speed of understanding [Link]
The isupper() method in Python checks whether all alphabetic characters in a string are in uppercase (A–Z).
It returns True if all letters are uppercase and there is at least one alphabetic character; otherwise, it
returns False. This method is useful for validating input where uppercase letters are required.
42
2025-11-02
The isspace() method in Python checks whether all characters in a string are whitespace characters, such as spaces,
tabs (\t), or newlines (\n). It returns True if the string contains only whitespace and is not empty; otherwise, it returns
False. This method is useful when validating input to detect blank entries or to clean unnecessary spaces.
text1 = " " text2 = " \t\n " text3 = "Python "
print([Link]()) print([Link]()) print([Link]())
True True False
The istitle() method in Python checks whether each word in a string starts with an uppercase letter followed by
lowercase letters. It returns True if the string follows the title case format and is not empty; otherwise, it returns False.
This method is useful when validating names, book titles, or headings.
Example Example
text1 = "Python Programming" text2 = "python Programming"
print([Link]()) print([Link]())
True False
43
2025-11-02
Write a program that accepts any string and counts the number of alphabets & digits present in it.
Read a string from user and capitalise every alternate letter in the string, eg, PaSsIoN becomes pAsSiOn.
44
2025-11-02
Thank You
For Watching!
Please share your suggestions related to the
video in the comments.
45
2025-11-02
Subscribe Now
And be a part of our Family
Please share your suggestions related to the
video in the comments.
46