What is Computer

Module: M2-R5: Web Design & Publishing

Chapter: Ch1 Computer Intro

🔹 Introduction

In Python, strings are sequences of characters enclosed within single, double, or triple quotes. Strings are one of the most commonly used data types and support a wide range of operations such as indexing, slicing, concatenation, repetition, and other useful methods.

🔹 String Indexing

Each character in a string has an index. Indexing starts from 0 for the first character and goes up to n-1. Negative indices count from the end, starting at -1.

text = "Python"
print(text[0]) # P
print(text[-1]) # n
🔹 String Slicing

Slicing extracts a portion of a string using the syntax string[start:end:step].

text = "PythonProgramming"
print(text[0:6]) # Python
print(text[6:]) # Programming
print(text[:6]) # Python
print(text[::2]) # PtoPormig
🔹 String Concatenation & Repetition

You can join strings together using concatenation with + and repeat them with *.

a = "Hello"
b = "World"
print(a + " " + b) # Hello World
print(a * 3) # HelloHelloHello
🔹 Common String Operations & Methods
  • len(s): Returns the length of the string.
  • lower()/upper(): Convert to lowercase or uppercase.
  • strip(): Removes leading/trailing whitespace.
  • replace(old, new): Replaces a substring.
  • split(): Splits string into a list based on a separator.
  • find(): Finds the index of a substring.
  • in operator: Checks if a substring exists in the string.
💻 Examples
1️⃣ Indexing & Slicing Example
word = "Python"
print(word[0])      # P
print(word[-1])     # n
print(word[0:4])    # Pyth
print(word[::2])    # Pto
2️⃣ Concatenation & Repetition Example
a = "Hi"
b = "There"
print(a + " " + b)   # Hi There
print(a * 4)         # HiHiHiHi
3️⃣ String Methods Example
text = "   Python Programming   "
print(len(text))          # 23
print(text.strip())       # Python Programming
print(text.upper())       # PYTHON PROGRAMMING
print(text.replace("Python", "Java"))  # Java Programming
print("Python" in text)   # True
📘 Summary
  • Strings in Python are sequences of characters enclosed in quotes.
  • Indexing and slicing allow access to individual or groups of characters.
  • Concatenation and repetition are simple operations using + and *.
  • Python provides many built-in string methods for manipulation and searching.
Quick Links