Skip to content

Instantly share code, notes, and snippets.

@cybersiddhu
Last active September 9, 2024 00:44
Show Gist options
  • Save cybersiddhu/cc16fa596bfbb991d1ad7c4ce155c128 to your computer and use it in GitHub Desktop.
Save cybersiddhu/cc16fa596bfbb991d1ad7c4ce155c128 to your computer and use it in GitHub Desktop.
python strings for freshman learning

Module 1: Introduction to Strings

Lesson 1: What are Strings?

  1. Definition of strings in Python
  2. How strings are used in programming
  3. Examples of strings in everyday life

Example:

# Examples of strings
name = "John Doe"
favorite_color = 'blue'
sentence = "I love programming!"

Lesson 2: Creating Strings

  1. Using single quotes
  2. Using double quotes
  3. Using triple quotes for multi-line strings

Example:

# Single quotes
single_quoted = 'Hello, World!'

# Double quotes
double_quoted = "Python is awesome!"

# Triple quotes
multi_line = """This is a
multi-line
string."""

print(single_quoted)
print(double_quoted)
print(multi_line)

Module 2: String Operations

Lesson 1: String Concatenation

  1. Explanation of concatenation
  2. Using the '+' operator
  3. Using the '+=' operator for in-place concatenation
  4. Using f-strings (Formatted String Literals)

Example:

# String concatenation
first_name = "Jane"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name)  # Output: Jane Smith

# In-place concatenation
greeting = "Hello"
greeting += ", "
greeting += "world!"
print(greeting)  # Output: Hello, world!

# Using f-strings
name = "Alice"
age = 30
introduction = f"My name is {name} and I am {age} years old."
print(introduction)

# F-strings with expressions
x = 10
y = 20
result = f"The sum of {x} and {y} is {x + y}."
print(result)

print("\nStep-by-step:")
print("1. We have variables name =", name, "and age =", age)
print("2. We create an f-string with {name} and {age}")
print("3. Result:", introduction)
print("4. We use an f-string with an expression {x + y}")
print("5. Expression result:", result)

Lesson 2: String Repetition

  1. Explanation of string repetition
  2. Using the '*' operator

Example:

# String repetition
star_line = "*" * 20
print(star_line)  # Output: ********************

word = "Hip "
cheer = word * 3 + "Hooray!"
print(cheer)  # Output: Hip Hip Hip Hooray!

Module 3: String Indexing and Slicing

Lesson 1: String Indexing

  1. Explanation of indexing in Python
  2. Positive indexing (from left to right)
  3. Negative indexing (from right to left)

Example:

# String indexing
text = "Python"
print(text[0])   # Output: P (first character)
print(text[2])   # Output: t (third character)
print(text[-1])  # Output: n (last character)
print(text[-3])  # Output: h (third-to-last character)

Lesson 2: String Slicing

  1. Explanation of slicing
  2. Basic slicing syntax: [start:end]
  3. Extended slicing syntax: [start:end:step]

Example:

# String slicing
text = "Programming"
print(text[0:4])    # Output: Prog
print(text[5:])     # Output: amming
print(text[:5])     # Output: Progr
print(text[::2])    # Output: Pormig (every second character)
print(text[::-1])   # Output: gnimmargorP (reversed string)

Module 4: String Methods

Lesson 1: Case Manipulation

  1. upper() method
  2. lower() method
  3. capitalize() method
  4. title() method

Example:

# Case manipulation methods
text = "hello, WORLD!"
print(text.upper())      # Output: HELLO, WORLD!
print(text.lower())      # Output: hello, world!
print(text.capitalize()) # Output: Hello, world!
print(text.title())      # Output: Hello, World!

Lesson 2: String Searching

  1. find() method
  2. index() method
  3. count() method

Example:

# String searching methods
sentence = "The quick brown fox jumps over the lazy dog"
print(sentence.find("quick"))    # Output: 4
print(sentence.index("fox"))     # Output: 16
print(sentence.count("the"))     # Output: 2 (case-sensitive)

Lesson 3: String Modification

  1. replace() method
  2. strip(), lstrip(), and rstrip() methods
  3. split() and join() methods

Example:

# String modification methods
text = "   Hello, World!   "
print(text.replace("World", "Python"))  # Output:    Hello, Python!   
print(text.strip())                     # Output: Hello, World!
print(text.lstrip())                    # Output: Hello, World!   
print(text.rstrip())                    # Output:    Hello, World!

words = "apple,banana,cherry"
fruit_list = words.split(",")
print(fruit_list)  # Output: ['apple', 'banana', 'cherry']

joined = "-".join(fruit_list)
print(joined)      # Output: apple-banana-cherry

Module 5: String Formatting

Lesson 1: Old-style String Formatting

  1. Using the % operator
  2. Format specifiers

Example:

# Old-style string formatting
name = "Alice"
age = 15
print("My name is %s and I'm %d years old." % (name, age))
# Output: My name is Alice and I'm 15 years old.

Lesson 2: New-style String Formatting

  1. Using the format() method
  2. Positional and keyword arguments

Example:

# New-style string formatting
name = "Bob"
age = 16
print("My name is {} and I'm {} years old.".format(name, age))
# Output: My name is Bob and I'm 16 years old.

print("My name is {name} and I'm {age} years old.".format(name=name, age=age))
# Output: My name is Bob and I'm 16 years old.

Lesson 3: F-strings (Formatted String Literals)

  1. Introduction to f-strings
  2. Embedding expressions inside f-strings

Example:

# F-strings
name = "Charlie"
age = 14
print(f"My name is {name} and I'm {age} years old.")
# Output: My name is Charlie and I'm 14 years old.

x = 10
y = 5
print(f"The sum of {x} and {y} is {x + y}.")
# Output: The sum of 10 and 5 is 15.

More

  1. Escape Characters in Strings
# Using escape characters
print("He said, \"Python is amazing!\"")  # Output: He said, "Python is amazing!"
print('It\'s a beautiful day.')           # Output: It's a beautiful day.
print("This is a new line.\nAnd this is another line.")
# Output:
# This is a new line.
# And this is another line.

print("Tab\tSpace")  # Output: Tab     Space
print("Backslash: \\")  # Output: Backslash: \
  1. Raw Strings
# Raw strings ignore escape characters
print(r"C:\Users\John\Documents")  # Output: C:\Users\John\Documents
print(r"This is a \n new line")    # Output: This is a \n new line
  1. String Methods for Checking Content
# Various string checking methods
text = "Python Programming 101"

print(text.startswith("Python"))  # Output: True
print(text.endswith("201"))       # Output: False
print(text.isalpha())             # Output: False (contains spaces and numbers)
print(text.isalnum())             # Output: False (contains spaces)
print(text.isdigit())             # Output: False
print(text.istitle())             # Output: True
print(text.isupper())             # Output: False
print(text.islower())             # Output: False

number = "12345"
print(number.isnumeric())         # Output: True
  1. Advanced String Slicing
text = "abcdefghijklmnopqrstuvwxyz"

# Slicing with different step sizes
print(text[::2])   # Output: acegikmoqsuwy
print(text[1::2])  # Output: bdfhjlnprtvxz

# Negative step for reverse order
print(text[::-1])  # Output: zyxwvutsrqponmlkjihgfedcba
print(text[-3::-2])  # Output: xvtrpnljhfdb

# Slicing with negative indices
print(text[-5:-2])  # Output: vwx
  1. String Alignment and Padding
# String alignment methods
text = "Python"
print(text.ljust(10, '-'))   # Output: Python----
print(text.rjust(10, '*'))   # Output: ****Python
print(text.center(10, '='))  # Output: ==Python==

# Zero padding for numbers
number = "42"
print(number.zfill(5))  # Output: 00042
  1. Advanced String Formatting
# Formatting with width and precision
pi = 3.14159
print(f"Pi to 2 decimal places: {pi:.2f}")  # Output: Pi to 2 decimal places: 3.14
print(f"Pi in scientific notation: {pi:e}")  # Output: Pi in scientific notation: 3.141590e+00

# Formatting with alignment
for i in range(1, 6):
    print(f"{i:2d} {i*i:3d} {i*i*i:4d}")
# Output:
#  1   1    1
#  2   4    8
#  3   9   27
#  4  16   64
#  5  25  125

# Formatting dates
import datetime
now = datetime.datetime.now()
print(f"Current date: {now:%Y-%m-%d}")  # Output: Current date: 2023-09-02
print(f"Current time: {now:%H:%M:%S}")  # Output: Current time: 21:32:25
  1. String Comparison
# String comparison
print("apple" < "banana")  # Output: True
print("cherry" > "banana")  # Output: True
print("Apple" == "apple")  # Output: False (case-sensitive)
print("Apple".lower() == "apple")  # Output: True

# Comparing strings alphabetically
fruits = ["banana", "apple", "cherry", "date"]
sorted_fruits = sorted(fruits)
print(sorted_fruits)  # Output: ['apple', 'banana', 'cherry', 'date']
  1. String Encoding and Decoding
# String encoding and decoding
text = "Hello, 世界"
encoded = text.encode('utf-8')
print(encoded)  # Output: b'Hello, \xe4\xb8\x96\xe7\x95\x8c'

decoded = encoded.decode('utf-8')
print(decoded)  # Output: Hello, 世界
  1. String Interpolation with Dictionary
# String interpolation using a dictionary
person = {"name": "Alice", "age": 30, "city": "New York"}
message = "My name is %(name)s, I'm %(age)d years old, and I live in %(city)s."
print(message % person)
# Output: My name is Alice, I'm 30 years old, and I live in New York.
  1. Working with Substrings
# Finding all occurrences of a substring
text = "Mississippi"
sub = "ss"
start = 0
while True:
    start = text.find(sub, start)
    if start == -1:
        break
    print(f"Found '{sub}' at index {start}")
    start += len(sub)
# Output:
# Found 'ss' at index 2
# Found 'ss' at index 5

# Replacing multiple occurrences
text = "The quick brown fox jumps over the lazy dog"
new_text = text.replace("the", "a").replace("The", "A")
print(new_text)
# Output: A quick brown fox jumps over a lazy dog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment