Chapter 6: Strings in Python

Introduction to Strings

Immutable

A string object always represents the same string. Once created, strings cannot be modified.

Strings are sequences of UNICODE characters that may include letters, numbers, special characters, white-space, or backslashes. Strings are enclosed with single quotes (' '), double quotes (" "), or triple quotes (''' ''').

"Hello Python"

'Hello Python'

''' Hi Hello Python1234'''

Creating Strings

Basic String Creation

A = "Good Morning"
X = "Write article on \"AI\" briefly"
print(X)  # Output: Write article on "AI" briefly

Empty String

str = ""
str = ' '
print(str)  # Output: ' '

Multiline String

A = ''' This is a 
Multiline String 
Example'''
print(A)  # Output: This is a Multiline String Example

String Indexing and Traversing

Accessing all elements of a string one after another using subscript or index values.

Example: str = "HELLO PYTHON"

Positive Index (Forward)

H E L L O P Y T H O N

0 1 2 3 4 5 6 7 8 9 10 11

Negative Index (Backward)

H E L L O P Y T H O N

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

str = "Hello Python"
print(str[4])   # Output: o
print(str[-1])  # Output: n

Special String Operators

String Operators

  • 1. Slicing → String[range]
  • 2. Concatenation → String1 + String2
  • 3. Repetition → String1 * x
  • 4. Membership → in, not in
  • 5. Reverse → String[::-1]
  • 6. Comparison → <, >, <=, >===, !=

1. Slicing [start:stop:step]

Note: stop = stop - 1

s = "HELLO PYTHON"
print(s[1:5])    # Output: ELLO
print(s[0:8])    # Output: HELLO PY
print(s[1:9:-1]) # Output: (empty string)

2. Concatenation (+)

Joining two strings together.

str = "GOOD"
str1 = "Morning"
print(str + str1)           # Output: GOODMorning
print("Python" + "Program") # Output: PythonProgram
print("Python" + " " + "Program") # Output: Python Program
print("Python" + "10")      # Output: Python10

# Error example:
# print("Python" + 10)  # TypeError: can only concatenate str (not "int") to str

3. Repetition (*)

str = "Hi !!! "
print(str * 3)        # Output: Hi !!! Hi !!! Hi !!! 
print("Hello" * 2)    # Output: HelloHello
print(3 * "Hi")       # Output: HiHiHi
print(3 * 2 * "Hi")   # Output: HiHiHiHiHiHi
print('AI!' * 2 * 2)  # Output: AI!AI!AI!AI!

# Error example:
# print('Hi' * 'Hello')  # TypeError: can't multiply sequence by non-int

4. Membership (in, not in)

str = "HELLO PYTHON"
print('LLO' in str)      # Output: True
print('aa' in str)       # Output: False
print('zz' in str)       # Output: False
print('abc' not in str)  # Output: True
print('py' not in str)   # Output: True
print('Py' not in str)   # Output: True

5. Reverse

str = "HELLO PYTHON"
print(str[::-1])  # Output: NOHTYP OLLEH

6. Comparison

print('apple' > 'a')      # Output: True
print('apple' > 'A')      # Output: True
print('Apple' > 'a')      # Output: False
print('Apple' >= 'z')     # Output: False
print('Apple' == 'apple') # Output: False
print('apple' == 'apple') # Output: True
print('apple' != 'apple') # Output: False

a = 'python'
b = 'apple'
print(a > b)              # Output: True

String Methods and Built-in Functions

1. len() - Length of String

a = "PYTHON"
print(len(a))  # Output: 6

2. capitalize() - First Letter Uppercase

a = "python"
print(a.capitalize())  # Output: Python

a = "python programming language"
print(a.capitalize())  # Output: Python programming language

3. split() - Split String into List

Syntax: str.split([separator[, maxsplit]])

x = "Red$blue$green"
print(x.split("$"))  # Output: ['Red', 'blue', 'green']

g = "red:blue:orange:pink"
print(g.split(':', 2))  # Output: ['red', 'blue', 'orange:pink']
print(g.split(':', 1))  # Output: ['red', 'blue:orange:pink']
print(g.split(':', 0))  # Output: ['red:blue:orange:pink']

4. replace() - Replace Substring

x = "This is a String Example"
print(x.replace("is", "was"))  # Output: Thwas was a String Example

5. find() - Find Substring Index

Returns -1 if substring not found.

str = "Green Revolution"
print(str.find("green"))    # Output: -1
print(str.find("Green"))    # Output: 0
print(str.find("een"))      # Output: 2
print(str.find("n", 3, 20)) # Output: 4
print(str.find("n", 5, 20)) # Output: 15

6. index() - Find Index (Raises Exception)

Similar to find() but raises ValueError if substring not found.

str = "Hello ITS all about STRINGS!!!"
print(str.index('Hello'))  # Output: 0
print(str.index('ll'))     # Output: 2
print(str.index("all"))    # Output: 10

# Error example:
# print(str.index('abc'))  # ValueError: substring not found

7. isalpha() - Check for Alphabets Only

str = "Good"
print(str.isalpha())     # Output: True

str = "123good"
print(str.isalpha())     # Output: False

8. isalnum() - Check for Alphanumeric

str = "Good"
print(str.isalnum())        # Output: True

str = "123Good"
print(str.isalnum())        # Output: True

str = "Good Morning"
print(str.isalnum())        # Output: False (space is not alphanumeric)

9. isdigit() - Check for Digits Only

str = "12345"
print(str.isdigit())     # Output: True

str = "123Good"
print(str.isdigit())     # Output: False

10. title() - Title Case

str = "hello ITS all about STRINGS"
print(str.title())  # Output: Hello Its All About Strings

11. count() - Count Substring Occurrences

str = "Hello Hi Python Hello World Hi Welcome"
print(str.count("Hello", 12, 40))  # Output: 1
print(str.count("Hi", 2, 40))      # Output: 2

12. lower() - Convert to Lowercase

str = "Learning Python"
print(str.lower())  # Output: learning python

str = "PYthON"
print(str.lower())  # Output: python

13. islower() - Check if Lowercase

str = "Learning Python"
print(str.islower())  # Output: False

str = "python"
print(str.islower())  # Output: True

14. upper() - Convert to Uppercase

str = "Learning Python"
print(str.upper())  # Output: LEARNING PYTHON

str = "python"
print(str.upper())  # Output: PYTHON

15. isupper() - Check if Uppercase

str = "PYTHON"
print(str.isupper())  # Output: True

str = "PYTHOn"
print(str.isupper())  # Output: False

16. lstrip() - Remove Left Spaces

str = "    Green REvolution"
print(str.lstrip())  # Output: Green REvolution

str = "Green REvolution"
print(str.lstrip("Gr"))  # Output: een REvolution

17. rstrip() - Remove Right Spaces

str = "Green Revolution    "
print(str.rstrip())  # Output: Green Revolution

str = "Green Revolution"
print(str.rstrip("tion"))  # Output: Green Revolu

18. strip() - Remove Both Side Spaces

str = "   Hello ITS all about STRINGS     "
print(str.strip())  # Output: Hello ITS all about STRINGS

19. isspace() - Check for Whitespace Only

str = "   "
print(str.isspace())  # Output: True

str = "Hello ITS all about STRINGS"
print(str.isspace())  # Output: False

20. istitle() - Check if Title Case

str = "All Learn Python"
print(str.istitle())  # Output: True

str = "All Learn python"
print(str.istitle())  # Output: False

21. join() - Join Sequence with Separator

str = "12345"
s = '-'
print(s.join(str))  # Output: 1-2-3-4-5

s = '*'
print(s.join(str))  # Output: 1*2*3*4*5

s = '****'
print(s.join(str))  # Output: 1****2****3****4****5

22. swapcase() - Swap Case

str = "Welcome"
print(str.swapcase())  # Output: wELCOME

str = "PYTHon"
print(str.swapcase())  # Output: pythON

str = "PYTHON"
print(str.swapcase())  # Output: python

23. partition() - Split into 3 Parts

str = "xyz@gmail.com"
print(str.partition("@"))  # Output: ('xyz', '@', 'gmail.com')
print(str.partition("."))  # Output: ('xyz@gmail', '.', 'com')
print(str.partition("g"))  # Output: ('xyz@', 'g', 'mail.com')

Other Important Functions

1. ord() - ASCII/Unicode Value

ch = 'A'
print(ord(ch))  # Output: 65

ch = 'a'
print(ord(ch))  # Output: 97

2. chr() - Character from ASCII/Unicode

print(chr(97))  # Output: a
print(chr(65))  # Output: A

Jump Statements

1. Break Statement

The break statement terminates the current loop. If break statement is inside a nested loop, break will terminate the innermost loop.

for val in "String":
    if val == 'i':
        break
    print(val)
print("end")

# Output:
# S
# t
# r
# end

2. Continue Statement

When a continue statement is encountered, the control jumps to the beginning of the loop for next iteration.

for val in "String":
    if val == 'i':
        continue
    print(val)
print("end")

# Output:
# S
# t
# r
# n
# g
# end

3. Pass Statement

It is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes.

S = ['p', 'y', 't', 'h', 'o', 'n']
for v in S:
    pass  # Nothing happens, just a placeholder

# Syntax: pass

Local and Global Declaration

Note: This topic will be covered in detail in the Functions chapter. Local variables are accessible within the function where they are declared, while global variables can be accessed throughout the program.

Mutable and Immutable Objects

Mutable

Objects CAN be changed after creation

  • • List
  • • Dictionary
  • • Set
  • • User defined classes

Immutable

Objects CAN'T be changed after creation

  • • Tuple
  • • String
  • • Numbers (int, float)
  • • Boolean

Important Note

Strings are immutable in Python. When you perform operations like concatenation or replacement, a new string object is created rather than modifying the existing one.

Practice Examples

Example 1: String Slicing

X = "AmaZing"
# Index:  0123456
# Index: -7-6-5-4-3-2-1

print(X[3:], "and", X[:2])      # Output: Zing and Am
print(X[-7:], "and", X[-4:-2])  # Output: AmaZing and Zi
print(X[2:7], "and", X[-4:-1])  # Output: aZing and Zin

Example 2: String Operations

x = "1bzz"
print(x[0:3] + 'c')  # Output: 1bzc

# Finding substring
text = "green vegetables"
print(text.find('g', 2))  # Output: 8 (finds 'g' starting from index 2)

Related Resources

Need Help?

Join our tuition classes for personalized guidance on Python programming.

Register for Classes →

Practice More

Try string manipulation exercises to strengthen your Python skills.

View Practical Programs →