Strings in Python
In Python, a string is a sequence of characters, such as letters, numbers,
or symbols, enclosed within quotes. Strings are a fundamental data type
used for representing and manipulating text.
Key characteristics of Python strings:
● Creation: Strings can be created using single quotes ('...'), double
quotes ("..."), or triple quotes ('''...''' or """..."""). Triple quotes are
typically used for multi-line strings.
1. Single quotes: 'Hello'
2. Double quotes: "World"
3. Triple quotes: """This allows for
multiline strings and
preserves line breaks"""
example:
single_quoted = 'This is a string.'
double_quoted = "This is also a string."
multi_line = """This is a
multi-line string."""
● Immutability: Python strings are immutable, meaning that once a
string is created, its content cannot be changed. Any operation that
appears to modify a string, such as concatenation or replacement,
actually creates a new string.
example:
s = "hello"
# s[0] = 'H' # This would raise a TypeError
new_s = s + " world" # Creates a new string "hello world"
● Indexing and Slicing: Characters within a string can be accessed
using zero-based indexing, where the first character is at index 0.
Slicing allows extracting a portion of a string.
example:
my_string = "Python"
print(my_string[0]) # Output: P
print(my_string[1:4]) # Output: yth
● Concatenation: Strings can be joined together using the + operator.
example
greeting = "Hello"
name = "Alice"
full_message = greeting + ", " + name + "!" # Output: Hello, Alice!
Points to remember
- String is Immutable
- String allocates Continuous memory
- String store data in the form of Characters
- String is sequence data type
- String have Indexes
- Positive 0 to n-1 (Left to right)
- Negative -1 to -n (right to left)
- Each character have a unique index
- [index] is used individual character
String operators
1. Concatenation operator +
a. Both sides you should have strings
b. You use str() to convert numeric value to a string
c. example
S=”abc”+”def”
S=”abc”+str(123)
Wrong
S=”abc”+123
2. Repetition or replication operator *
a. One side numeric (int) value and other side should be string
b. example
“abc”*2
2*”abc”
Wrong
“abc”*”def”
3. Membership operator
a. In and not in
b. If “a” in S:
4. Comparison
a. Relation >,<
b. Comparison is done from ASCII value
Remember ASCII value if A - 65 , a - 97, 0 - 48
String comparison in Python is a straightforward process that evaluates strings
character by character based on their lexicographical (alphabetical) order, using
the ASCII values of the characters involved.
Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Here is a detailed breakdown of how these operators work:
1. Equality Comparison (== and !=)
This is the simplest comparison. Two strings are equal only if they have the exact
same characters in the exact same order, and are case-sensitive.
example
str1 = "apple"
str2 = "apple"
str3 = "Apple" # Note the capital 'A'
str4 = "banana"
print(str1 == str2) # Output: True
print(str1 == str3) # Output: False (case sensitive)
print(str1 != str4) # Output: True
2. Lexicographical Comparison (Alphabetical Order)
When you use >,<, >=, or <=, Python compares strings character by character from
left to right. The comparison stops as soon as a difference is found.
How it works:
● Rule 1: The first differing character decides the outcome.
Python looks at the ASCII (or Unicode) value of each character. A character
with a higher ASCII value is considered "greater".
Example
# 'b' comes after 'a' in the alphabet, so "banana" > "apple"
print("banana" > "apple") # Output: True
# 'c' vs 'b' is compared first: 'c' has a higher value than 'b'
print("cat" > "bat") # Output: True
● Rule 2: Case sensitivity matters.
All uppercase letters have lower ASCII values than all lowercase letters. This
is a common point of confusion for beginners.
Example
# ASCII of 'Z' is 90
# ASCII of 'a' is 97
print("Zebra" < "apple") # Output: True ("Z" is less than "a")
● Rule 3: Length only matters if the prefix is identical.
If one string is a prefix of another (e.g., "app" and "apple"), the longer string
is considered greater.
Example
print("app" < "apple") # Output: True
print("apple" > "app") # Output: True
print("app" == "app") # Output: True
Summary Table of Lexicographical Rules:
Code Explanation Result
"a" < "b" 'a' is before 'b' True
"A" < "a" Uppercase letters have lower ASCII values True
"apple" < "banana" Compares 'a' vs 'b' first True
"cat" > "car" Compares 't' vs 'r' (t is > r) True
"hello" == "Hello" Case mismatch False
"hi" < "hi there" Prefix rule (length matters) True
5. Conversion function
a. chr() → ASCII value is converted into a character
S=chr(65)
print(S)
A
Implement - pattern printing
A
AB
ABC
ABCD
for a in range(65,76):
for b in range(65,a+1):
print(chr(b),end=” “)
print()
b. ord() → return ASCII value of a character
print(ord(‘C’))
67
String Slicing in Python
String slicing in Python is a powerful technique used to access a sequence of
characters within a string, rather than just a single character. It allows you to
extract substrings efficiently.
Slicing uses the same square bracket notation as indexing, but with one or two
colons inside the brackets: [start:stop:step].
The most common form of slicing uses the start and stop parameters.
● start: The index where the slice begins (inclusive). If omitted, it defaults to
the beginning of the string (index 0).
● stop: The index where the slice ends (exclusive). The character at this index
is not included in the result.
● step (optional): Determines how many characters to skip. If omitted, it
defaults to 1.
S=”Computer Science”
Positive → → →
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
C o m p u t e r S c i e n c e
-1 -1 -1 -1 -1 -1 -1 -9 -8 -7 -6 -5 -4 -3 -2 -1
6 5 4 3 2 1 0
Negative ← ← ←
1. No parameter
[:]
[::]
Displays the complete string
[::] start=0 end ==len(S) step =1
for a in range(0,len(S)):
[::-1] start =len(S)-1 or -len(S) end =-1 or -len(S)-1 step =-1
2. Only start parameter
Ends at len(S)
S[2:] from this index till end
S[-13: ]
p u t e r S c i e n c e
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
3. Only end parameter
Begins from 0
S[:8]
0 1 2 3 4 5 6 7
C o m p u t e r
S[:-7]
C o m p u t e r S
-16 -15 -14 -13 -12 -11 -10 -9 -8 -7
4. Only step parameter
● If positive step start is 0 and end is leng(string)-1
Eg
S[::2]
0 2 4 6 8 10 12 14
C m u e c e c
Output : Cmue cec
● If negative step start is len(string)-1 and end is 0, reverse order
S[::-1]
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
C o m p u t e r S c i e n c e
Output: ecneicS retupmoC
5. Start and end both
S[2:10]
2 3 4 5 6 7 8 9 10
m p u t e r S c
S[-10:-1]
e r S c i e n c
-10 -9 -8 -7 -6 -5 -4 -3 -2
Remember : Start must lie on left of end
S[-1:-9]
“” or empty
6. Start, end, step
a. Positive step
Start left of end
S[1:10:2]
1 3 5 7 9
o p t r S
b. Negative step
Start must be in right of end
Order will be reverse
S[10:1:-2]
2 4 6 8 10
m u e c
←←←←
ceum
Remember:
A. Omitted start or stop values
When you leave out the start or stop index, Python automatically uses the
boundaries of the string:
Example
my_string = "Python Slicing"
# Get the first 6 characters (start defaults to 0)
print(my_string[:6]) # Output: "Python"
# Get from index 7 to the end (stop defaults to the end)
print(my_string[7:]) # Output: "Slicing"
# Get the entire string (both start and stop are omitted)
print(my_string[:]) # Output: "Python Slicing"
B. Using Negative Indices
Negative indices count from the end of the string. The last character is
index -1, the second to last is -2, and so on.
example
my_string = "Python"
# Get the last two characters
print(my_string[-2:]) # Output: "on"
# Get everything except the last character
print(my_string[:-1])# Output: "Pytho"
# Slice from the third character from the end up to the end
print(my_string[-3:])# Output: "hon"
3. The step Parameter
The third parameter determines the increment between indices. It defaults
to 1.
Example
my_string = "0123456789"
# Step by 2: start at 0, go to the end, picking up every second character
print(my_string[0::2]) # Output: "02468"
# Step by 3: start at index 1, stop at index 8 (exclusive)
print(my_string[1:8:3])# Output: "147"
The Most Common Use of step: Reversing a String
Using a step of -1 is the standard Pythonic way to reverse a string:
python
greeting = "hello"
# Start at the end, go to the beginning, step backwards by 1
print(greeting[::-1]) # Output: "olleh"
Summary of Slicing Rules
Syntax Description
s[i:j] Slice from index i to j-1
s[i:] Slice from index i to the len(list)
s[:j] Slice from the 0 to index j-1
S[:] A copy of the entire string
S[::]
s[::k] Slice from 0 to len(list), stepping by k if k is positive and
slice from len(list)-1 to 0 if k is negative
s[::-1] Reverse the string
S[i::Step] If Step is positive from 0 to len(list)
If Step is negative from i to 0 in reverse order
s[:j:Step] If Step is positive from 0 to j-step
If Step is negative from from j to 1 in reverse order
Example
S=”Computer Science”
Slicing using indexes
S[1:4] omp
S[7:] r Science
S[:6] Comput
S[::2] Cmue cec
S[5:-1] ter Scienc
S[::-1] reverse order
[First index should be on left of second index value]
Can give right ONLY when you give step value as negative
S[7:1] No output
S[7:1:-1] get in reverse order
S=input(“Enter The string:”)
S1=S[::-1]
if S == S1:
print(“Palindrome”)
else:
print(“Not Palindrome”)
Loop to refer the data of a String (each character or character wise)
1. Refer each character
for x in S:
Where S is String
And x will one character at time
Can’t refer in the reverse order
2. Refer index of each character
for i in range(0,len(S)):
To get a character use []
S[i] to get the character
Can refer in reverse order
Can skip character
Function in String
● len() → returns the length of the string
S=”hello”
print(len(S)) displays 5
● str() → convert numeric to string
print(“ab”+str(5)) display ab5
Methods of <class ‘str’> : String
● count() → count number of times a substring occurs in the main
string
S=”abcdabcdab”
a. Count with a substring
x=[Link](“ab”)
3
b. Count with the start value
x=[Link](“ab”,5)
5th index onwards it will count
1
c. Count with start and end value
Check in that range
x=[Link](“ab”,3,7)
1
d. If the data is not present then it returns 0
● Index → starting index of the substring
a. index with a substring
x=[Link](“ab”)
0
b. index with the start value
x=[Link](“ab”,5)
5th index onwards it will search
8
c. index with start and end value
Check in that range
x=[Link](“ab”,3,7)
4
d. If the data is not present then it gives syntax error
Program
S=input(“Enter the string”)
D=input(“Enter substring to search:”)
if [Link](D) ==0:
print(D,” is not found in “,S)
else:
print(D,” is fount at “,[Link](D),” position”)
● Find → returns the lowest index of the string where it is found and
● find with a substring
x=[Link](“ab”)
0
● Find with the start value
x=[Link](“ab”,5)
5th index onwards it will count
8
● find with start and end value
Check in that range
x=[Link](“ab”,3,7)
4
● If the data is not present then it returns-1
● startswith() → whether a given string starts with a specific prefix. It
helps in efficiently verifying whether a string begins with a certain
substring.
Eg
S=”hello friends”
print([Link](‘s’))
Display False
● endswith() → checking if a string ends with a particular substring. It
can handle simple checks, multiple possible endings and specific
ranges within the string
Eg
S=”hello friends”
print([Link](‘s’))
Display True
● Check functions
a. isupper() → all the alphabets are in uppercase
S=”ABC”
[Link]() True
S=”AbC”
[Link]() False
S=”U123”
[Link]() True
S=”123t”
[Link]() False
b. islower() → all the alphabets present in the string are in lower
case
c. isdigit() → all the characters in the string can be digits
d. isalpha() →both upper and lower case character
e. isspace() → check if the string or character is a space
S=” “
[Link]() True
S=”” #empty string
[Link]() False
f. isalnum() → alphabets as well numbers
not [Link]() → for special characters
Program to count number of upper case character
S=input(“Enter the string:”)
Count=0
for a in S:
if [Link]():
Count+=1
print(“Number of uppercase characters are”,Count)
● Conversion
a. upper() → return the string after converting into upper case
b. lower() → returns the string after converting into lowercase
Program to accept a string and convert into uppercase
S=input(“Enter a String:”)
S1=””
for a in S:
if [Link]():
S1=S1+[Link]()
else:
S1=S1+a
print(“Converted string:”,S1)
c. swapcase() →change uppercase to lowercase and lowercase
to uppercase
d. title() → convert text in title case where first letter of each
word to uppercase
Eg
s=”ajay kapoor”
print([Link]())
Display
Ajay Kapoor
e. Capitalize() → return the string after converting the first
character as capital
S=[Link]()
Computer science
[Link]()
Nothing will change
S=S[0].upper()+S[1:]
● Removing spaces
a. lstrip() → removes spaces in the left of string or leading spaces
b. rstrip() → removes spaces from right of string or trailing spaces
c. strip() → removes spaces from both right and left.
● split() → splits a string into a list of strings after breaking the given string by
the specified separator.
Parameters
- separator: This is a delimiter. The string splits at this specified
separator. If it is not provided then any white space is a separator.
- maxsplit: It is a number that tells us to split the string into a
maximum of the provided number of times. If it is not provided then
the default is -1 which means there is no limit. [Note not in
Curriculum]
Returns
Returns a list of strings after breaking the given string by the specified
separator.
How to use string split() method in Python?
Using the list split() method is very easy, just call the split() function with a
string object and pass the separator as a parameter. Here we are using the
Python String split() function to split different Strings into a list, separated
by different characters in each case.
Example: In the above code, we have defined the variable 'text' with the
string 'geeks for geeks' then we called the split() method for 'text' with no
parameters which split the string with each occurrence of whitespace.
eg
text = 'Computer Science Examination'
# Splits at space
print([Link]()) [“Computer”,”Science”,Examination”]
word = 'Apple,Banana,Grapes'
# Splits at ','
print([Link](',')) [“Apple”,”Banana”,”Grapes”]
word = 'CatBatSatFatOr'
# Splitting at t
print([Link]('t')) ['Ca', 'Ba', 'Sa', 'Fa', 'Or']
● partition() → method is a handy tool when we need to split a string into
exactly three parts based on the first occurrence of a given separator.
○ It returns a tuple containing:
■ The part before the separator
■ The separator itself
■ The part after the separator
○ This is especially useful when we're parsing strings like filenames,
email addresses, key-value pairs, or structured messages where we're
expecting a predictable format with a known delimiter.
Eg
s = "Computer@Science@Examination"
res = [Link]("@")
print(res)
Output
(“Computer”,”@”,”Science@Examination”)
Explanation: partition("for") splits the string s at the first occurrence of
"for". It returns a tuple with three parts:
Syntax
[Link](separator)
○ Parameters:
■ separator(required): a substring that separates the string
○ Return Type:
■ Returns a tuple of three strings: (before_separator, separator,
after_separator).
○ If the separator is not found, the tuple returned is (string, '', '').
● join () → method is used to concatenate elements of an iterable (like
a list, tuple, or set) into a single string. It uses the string it's called on
as a separator between the elements.
Syntax
[Link](iterable)
Example
words = ["Hello", "world", "this", "is", "Python"]
sentence = " ".join(words)
print(sentence)
# Output: Hello world this is Python
Built-in functions of string:
S. Function Description Example
No.
>>>print(len(str))
1 len( ) Returns the length of a string 14
>>> [Link]()
2 capitalize( ) Returns the copy of the string with 'Hello365'
its first character capitalized and
the rest
of the letters are in lowercased.
Returns the index of the first >>>[Link]("thon",1,7)
3 find(sub,start, 3
occurrence of a substring in the
en d)
given string (case-sensitive). If the
>>> [Link]("ruct",8,13)
substring is not found it returns -1.
-1
>>>[Link]( )
4 isalnum( ) Returns True if all characters in the True
string are alphanumeric (either >>>[Link]( )
alphabets or numbers). If not, it True
returns False. >>>[Link]( )
True
>>>[Link]( )
False
>>>[Link]( )
False
>>>[Link]( )
5 isalpha( ) Returns True if all characters in the False
string are alphabetic. False >>>[Link]( )
otherwise. True
>>>[Link]( )
False
>>>[Link]( )
False
>>>[Link]( )
False
>>>[Link]( )
6 isdigit( ) Returns True if all the characters in False
the string are digits. False >>>[Link]( )
otherwise. False
>>>[Link]( )
True
>>>[Link]( )
False
>>>[Link]( )
False
>>> [Link]()
7 islower( ) Returns True if all the characters in True
the string are lowercase. False >>> [Link]()
otherwise. True
>>> [Link]()
False
>>> [Link]()
False
>>> [Link]()
True
8 >>> [Link]() False
isupper( ) Returns True if all the >>> [Link]() False
characters in the string are >>> [Link]() False
uppercase. False otherwise. >>> [Link]() False
>>> [Link]() False
9 >>> " ".isspace() True
isspace( ) Returns True if there are >>> "".isspace() False
only
1 >>> "HeLlo".lower() 'hello'
0 lower( ) Converts a string in lowercase
characters.
11 >>> "hello".upper() 'HELLO'
upper( ) Converts a string in uppercase
characters.
1 Returns a string after
2 lstrip( ) removing the leading >>> str="data structure"
characters. (Left side). if
>>> [Link]('dat') ' structure'
used without any argument,
>>> [Link]('data')' structure'
it removes theleading
>>> [Link]('at') 'data
whitespaces.
structure'
>>> [Link]('adt') ' structure'
>>> [Link]('tad') ' structure'
1 >>> [Link]('eur') 'data struct'
3 rstrip( ) Returns a string after removing >>> [Link]('rut') 'data
the trailing characters. (Right structure'
side). >>> [Link]('tucers')'data '
if used without any argument,
it removes the trailing
whitespaces.
1 Splits the string from the
4 split( ) specified separator and >>> str="Data Structure"
returns a list object with
string elements. >>> [Link]( ) ['Data',
'Structure']
Exercise Questions: String
1 Mark Questions
Q. Question Answer
No
1. print the string “India” 10 times. >>>”india”*10
2. False
What is the output of the following code
>>>‘a’ in “computer”
3. ‘cmue’
What is the output of the following code
Strg=”computer”
print(Strg[ 0: 8 : 2]
4. “India”
What is the output of the following?
print('INDIA'.capitalize())
5. Which of the following is not valid string in Python? (iii) “Hello’
(i) “Hello” (ii) ‘Hello’
(iii) “Hello’ (iv) None of the above
6. Suppose word = ‘amazing’, the what will ‘giaa’
be word[: : -2]?
2 Mark Questions
Sr. Question Answer
1.
If you give the following for str1=”Hello” why does python String is immutable
report error str1[2]=’p’ data [Link] it does
not support item
assignment
2. Identify the output of the following Python statements. Vidya
x="Vidyalaya" y="Vidya"
if(y in x):
print(y)
3. Look at the code sequence and select the correct output kvsrojAIPUR
str="KVS RO Jaipur" for i in str:
if([Link]()==True):
print([Link](),end="") if([Link]()==True):
print([Link](), end="")
4. -1
Find the correct output of the following
>>>str="The planet earth looks like a blue marble from outer
space"
>>>print([Link]('marble',50))
5. 12
Find the value stored in ctr at the end of this code snippet:
mystr="Darjeeling Tea has a strong flavour"
ctr=0
for i in mystr:
if i in 'aeiouAEIOU': ctr += 1
print(ctr)
3 Mark Questions
Sr. Question Answer
1. Write a Python program to input a line=input ("Enter a line of text :")
line of text and a character from ch=input ("Enter a character to search ")
user to print the frequency of the k=[Link](ch)
character in the line. For example
Line entered is : this is a print ("Frequency is :",k)
golden pen The character to
search : e
Then output is : Frequency is 2
2. Write a Python Program to input a s=input("Enter a word :")
string to check whether it is a print ("You entered :", s)
Palindrome string or not. (A length=len(s)
rev=""
Palindrome string is that which is
for i in range (-1,-length-1,-1):
same from both ends like – NITIN,
rev=rev+s[i]
MALAYALAM, PULLUP)
if s==rev:
print ("Yes, palindrome")
else:
print(“No, not a palindrome”)
3. for a in range(1,4):
Using string replication techniques print("hello " * a)
print the following pattern using any
loop.
Hello
Hello Hello
Hello Hello Hello
4 Mark Questions
S Question Answer
r.
1 Find Output: Jhu
. my_string = 'Jhunjhunu' J@H@U@N@J@H@
print(my_string[:3]) U@N@U@ Jhunjhunu
for i in range(len(my_string)): Njh
print(my_string[i].upper(),end="@")
print()
print (my_string)
print (my_string[3:6])
2 Comput
. Consider the following string mySubject: mySubject = er
"Computer Science" Science
Scienc
What will be the output of the following string C
operations : print(mySubject[0:len(mySubject)]) m
print(mySubject[-7:-1]) print(mySubject[::2]) u
print(mySubject[len(mySubject)-1]) e
c
print(2*mySubject)
e
print(mySubject[::-2]) c
e
Computer
ScienceComputer Science
eniSrtpo
3 a) Great India
. Consider the following string country: country= "Great
b) t Indi
India"
c)GetIda
d)a
What will be the output of the following string
operations(Any Four):- e) Great IndiaGreat India
a) print(country[0:len(country)])
b) print(country[-7:-1]) f) Great India
c) print(country[::2])
d) print(country[len(country)-1])
e) print(2*country)
f) print(country[:3] + country[3:])
WAP in Python to accept a String and convert all the lower case to upper
case
Find and write the output of the following python code:
def fun(s):
k=len(s)
m=" "
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
ese:
m=m+'bb'
print(m)
fun('school2@com')
output:
SCHOOLbbbbCOM
S=”computer”
S=S[0].upper()+S[1:]
print(S)
Computer
NOT ALLOWED
S[0]=S[0].upper()
Overwriting is not allowed