Python Strings

🐍 Python Strings

A Python Strings is a sequence of characters enclosed in:

  • "double quotes"

  • 'single quotes'

  • '''triple single quotes''' (multi-line)

  • """triple double quotes""" (multi-line)


✅ Creating Strings

name = "Python"
lang = 'Programming'
multiline = """This is
a multi-line string"""


📌 String Indexing

Strings are indexed, meaning each character has a position:

P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

Example:

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

🔄 String Slicing

You can extract parts of a string:

text = "Python Programming"
print(text[0:6]) # Python
print(text[:6]) # Python
print(text[7:]) # Programming
print(text[0:15:2]) # Every 2nd char

🏗️ Modifying Strings

Strings are immutable, but we can create new strings using built-in methods.

MethodDescriptionExample
upper()Convert to UPPERCASE"hello".upper()
lower()Convert to lowercase"HELLO".lower()
title()Each word Capitalized"python tutorial".title()
capitalize()First letter uppercase"hello world".capitalize()
strip()Remove spaces" hello ".strip()
replace()Replace text"Hello".replace("H", "J")

Example:

s = " hello python "
print(s.upper()) # HELLO PYTHON
print(s.strip()) # hello python
print(s.replace("hello", "Hi")) # Hi python

🔍 Python Strings Searching

MethodPurpose
find()Returns index of substring (or -1 if not found)
count()Counts occurrences
startswith()Checks beginning
endswith()Checks ending

Example:

msg = "Python is awesome"
print(msg.find("is")) # 7
print(msg.count("o")) # 2
print(msg.startswith("Py")) # True

🧩 Concatenation (+) & Repeating (*)

a = "Hello "
b = "World"
print(a + b) # Hello World
print(“Python! “ * 3) # Python! Python! Python!

🧵 String Formatting (Very Important)

1️⃣ f-strings (Best and Recommended)

name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")

2️⃣ format() method

print("My name is {} and I am {} years old.".format(name, age))

3️⃣ % formatting (old style)

print("My name is %s and I am %d" % (name, age))

🔠 String Escape Characters

EscapeMeaning
\"Double quote inside string
\'Single quote
\\Backslash
\nNew line
\tTab

Example:

print("Hello\nWorld")
print("He said: \"Python is easy\"")

🧪 Python Strings Methods Full List (Most Used)

text = "hello python"
print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
print(text.strip())
print(text.replace("hello", "hi"))
print(text.split()) # ['hello', 'python']
print(" ".join(["hello", "python"]))

🧠 String Functions Summary

OperationExampleResult
Lengthlen("Hello")5
Membership test"Py" in "Python"True
Iteratefor char in "hi": print(char)h i

⭐ Complete Mini Program

name = input("Enter your name: ").strip().title()

print(f”\nHello {name}! Welcome to Python Strings Tutorial. 😊”)
print(f”Your name contains {len(name)} characters.”)

You may also like...