0% found this document useful (0 votes)
3 views7 pages

Chapter 2 (Tutorial)

This tutorial covers advanced string manipulation in Python, including immutability, conversions, operators, indexing, and various string methods. Each section provides explanations, code examples, and exercises to reinforce learning. The chapter concludes with a summary of the key concepts and answers to the exercises.

Uploaded by

ariesvoldigord
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)
3 views7 pages

Chapter 2 (Tutorial)

This tutorial covers advanced string manipulation in Python, including immutability, conversions, operators, indexing, and various string methods. Each section provides explanations, code examples, and exercises to reinforce learning. The chapter concludes with a summary of the key concepts and answers to the exercises.

Uploaded by

ariesvoldigord
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

Chapter 2: Advanced String Capabilities in Python

Tutorial by Ayes Chinmay

July 22, 2025

Contents

1 Introduction 2

2 Strings Are Immutable 2

3 Numeric Conversions, Including Binary 2

4 String Operators (+, =, *, >, etc.) 2

5 Indexing and Slicing 3

6 Single-Character Functions (Character Codes) 3

7 Building Strings Using “join” 3

8 Important String Functions 3

9 Binary, Hex, and Octal Conversion Functions 4

10 Simple Boolean (“is”) Methods 4

11 Case Conversion Methods 4

12 Search-and-Replace Methods 5

13 Breaking Up Input Using “split” 5

14 Stripping 5

15 Justification Methods 6

16 Summary 6

17 Answers to Exercises 6

1
Advanced String Capabilities in Python - Chapter 2 Tutorial

1 Introduction
This tutorial covers Chapter 2, ”Advanced String Capabilities,” focusing on Python’s pow-
erful string manipulation features. You’ll learn about string immutability, conversions,
operators, indexing, and various string methods. Each section includes explanations,
code examples, and exercises.

2 Strings Are Immutable


Strings in Python are immutable, meaning their contents cannot be changed after cre-
ation. Any modification creates a new string.
1 text = ”Hello”
2 text = text + ” World” # Creates a new string
3 print(text)

Output:
Hello World
Exercise 1: Create a string greeting = ”Hi” and append ” there!” to it. Print the result.

3 Numeric Conversions, Including Binary


Convert strings to numbers using int(), float(), and convert numbers to binary strings
using bin().
1 num_str = ”123”
2 num = int(num_str)
3 binary = bin(num)[2:] # Remove ’0b’ prefix
4 print(f”Number: {num}, Binary: {binary}”)

Output:
Number: 123, Binary: 1111011
Exercise 2: Convert the string ”255” to an integer and print its binary representation.

4 String Operators (+, =, *, >, etc.)


String operators include concatenation (+), repetition (*), and comparison (>, <, ==).
1 str1 = ”Hello”
2 str2 = ”World”
3 concat = str1 + ” ” + str2
4 repeat = str1 * 2
5 print(f”Concatenation: {concat}”)
6 print(f”Repetition: {repeat}”)
7 print(f”Is str1 > str2? {str1 > str2}”)

Output:
Concatenation: Hello World
Repetition: HelloHello
Is str1 > str2? False
Exercise 3: Concatenate two strings and repeat the result three times.

2
Advanced String Capabilities in Python - Chapter 2 Tutorial

5 Indexing and Slicing


Strings are indexed (0-based) and can be sliced using [start:end:step].
1 text = ”Python”
2 print(f”First char: {text[0]}”)
3 print(f”Slice [1:4]: {text[1:4]})
4 print(f”Reverse: {text[::-1]}”)

Output:
First char: P
Slice [1:4]: yth
Reverse: nohtyP
Exercise 4: Extract the substring ”gram” from ”Programming”.

6 Single-Character Functions (Character Codes)


Use ord() to get a character’s Unicode code point and chr() to convert a code point to
a character.
1 char = ”A”
2 code = ord(char)
3 back = chr(code)
4 print(f”Character {char} has code {code}”)
5 print(f”Code {code} is character {back}”)

Output:
Character A has code 65
Code 65 is character A
Exercise 5: Find the Unicode code point of ’z’ and convert 97 back to a character.

7 Building Strings Using “join”


The join() method concatenates a list of strings with a separator.
1 words = [”Hello”, ”World”]
2 sentence = ” ”.join(words)
3 print(sentence)

Output:
Hello World
Exercise 6: Join the list [”apple”, ”banana”, ”orange”] with a comma and space.

8 Important String Functions


Key string methods include len(), upper(), lower(), and strip().
1 text = ” Python ”
2 print(f”Length: {len(text)}”)
3 print(f”Upper: {[Link]()}”)

3
Advanced String Capabilities in Python - Chapter 2 Tutorial

4 print(f”Lower: {[Link]()}”)
5 print(f”Stripped: ’{[Link]()}’”)

Output:
Length: 9
Upper: PYTHON
Lower: python
Stripped: ’Python’
Exercise 7: Apply upper() and strip() to ” hello ” and print the result.

9 Binary, Hex, and Octal Conversion Functions


Convert numbers to binary (bin()), hexadecimal (hex()), or octal (oct()).
1 num = 42
2 print(f”Binary: {bin(num)[2:]}”)
3 print(f”Hex: {hex(num)[2:]}”)
4 print(f”Octal: {oct(num)[2:]}”)

Output:
Binary: 101010
Hex: 2a
Octal: 52
Exercise 8: Convert 100 to hexadecimal and octal.

10 Simple Boolean (“is”) Methods


Methods like isalpha(), isdigit(), and isspace() test string properties.
1 text = ”Python123”
2 print(f”Is alpha? {[Link]()}”)
3 print(f”Is digit? {[Link]()}”)
4 print(f”Is alphanumeric? {[Link]()}”)

Output:
Is alpha? False
Is digit? False
Is alphanumeric? True
Exercise 9: Check if ”123” is a digit and if ”abc” is alphabetic.

11 Case Conversion Methods


Methods like upper(), lower(), title(), and capitalize() modify string case.
1 text = ”hello world”
2 print(f”Title: {[Link]()}”)
3 print(f”Capitalize: {[Link]()}”)

Output:

4
Advanced String Capabilities in Python - Chapter 2 Tutorial

Title: Hello World


Capitalize: Hello world
Exercise 10: Convert ”python programming” to title case.

12 Search-and-Replace Methods
Use find(), replace(), and count() for searching and replacing.
1 text = ”Hello World”
2 print(f”Find ’World’: {[Link](’World’)}”)
3 print(f”Replace: {[Link](’World’, ’Python’)}”)
4 print(f”Count ’l’: {[Link](’l’)}”)

Output:
Find ’World’: 6
Replace: Hello Python
Count ’l’: 3
Exercise 11: Replace ”cat” with ”dog” in ”The cat is on the mat”.

13 Breaking Up Input Using “split”


The split() method splits a string into a list based on a delimiter.
1 text = ”apple,banana,orange”
2 fruits = [Link](”,”)
3 print(fruits)

Output:
[’apple’, ’banana’, ’orange’]
Exercise 12: Split ”one two three” on spaces.

14 Stripping
Methods like strip(), lstrip(), and rstrip() remove whitespace.
1 text = ” Hello ”
2 print(f”Strip: ’{[Link]()}’”)
3 print(f”Left strip: ’{[Link]()}’”)
4 print(f”Right strip: ’{[Link]()}’”)

Output:
Strip: ’Hello’
Left strip: ’Hello ’
Right strip: ’ Hello’
Exercise 13: Strip whitespace from ” Python ”.

5
Advanced String Capabilities in Python - Chapter 2 Tutorial

15 Justification Methods
Methods like center(), ljust(), and rjust() align text.
1 text = ”Python”
2 print(f”Center: ’{[Link](10, ’*’)}’”)
3 print(f”Left justify: ’{[Link](10)}’”)
4 print(f”Right justify: ’{[Link](10)}’”)

Output:
Center: ’**Python**’
Left justify: ’Python ’
Right justify: ’ Python’
Exercise 14: Center ”Code” in a 10-character field with dashes.

16 Summary
This chapter covered advanced string manipulation in Python, including immutability,
conversions, operators, indexing, and various methods for processing strings. Practice
the exercises to master these concepts.

17 Answers to Exercises
1. Exercise 1:
1 greeting = ”Hi”
2 greeting = greeting + ” there!”
3 print(greeting)

2. Exercise 2:
1 num_str = ”255”
2 num = int(num_str)
3 print(bin(num)[2:])

3. Exercise 3:
1 str1 = ”Hello”
2 str2 = ”World”
3 result = (str1 + ” ” + str2) * 3
4 print(result)

4. Exercise 4:
1 text = ”Programming”
2 print(text[3:7])

5. Exercise 5:
1 print(ord(’z’))
2 print(chr(97))

6. Exercise 6:

6
Advanced String Capabilities in Python - Chapter 2 Tutorial

1 fruits = [”apple”, ”banana”, ”orange”]


2 print(”, ”.join(fruits))

7. Exercise 7:
1 text = ” hello ”
2 print([Link]().upper())

8. Exercise 8:
1 num = 100
2 print(hex(num)[2:])
3 print(oct(num)[2:])

9. Exercise 9:
1 print(”123”.isdigit())
2 print(”abc”.isalpha())

10. Exercise 10:


1 text = ”python programming”
2 print([Link]())

11. Exercise 11:


1 text = ”The cat is on the mat”
2 print([Link](”cat”, ”dog”))

12. Exercise 12:


1 text = ”one two three”
2 print([Link]())

13. Exercise 13:


1 text = ” Python ”
2 print([Link]())

14. Exercise 14:


1 text = ”Code”
2 print([Link](10, ’-’))

You might also like