Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
What are Variables?Numbers — Integers and FloatsNumber OperationsStrings — Creating and Using TextString FormattingBooleans and NoneType ConversionGetting User InputBest Practices
Python/Variables Data Types/Strings Creating Using

📝 Strings — Creating and Using Text

A string is text data enclosed in quotes. You can use single quotes ('hello'), double quotes ("hello"), or even triple quotes for multi-line text ("""hello"""). Strings are one of the most important data types because you'll use them constantly for displaying information, getting user input, and processing text. Python provides many built-in operations and methods for working with strings.


🎯 Creating Strings

You create a string by placing text inside quotes. Python doesn't care whether you use single or double quotes, but be consistent and match your opening and closing quotes. If your string contains a quote character, you can either use the other type of quote or escape it with a backslash.

# Different ways to create strings
name = "Alice"                    # Double quotes
greeting = 'Hello'                # Single quotes
message = "It's a great day!"     # Double quotes with apostrophe

# Multi-line strings
bio = """I'm learning Python.
It's really fun!
I can't wait to build projects."""

# Empty string
empty = ""

print(name)
print(greeting)
print(message)
print(bio)

➕ String Concatenation and Repetition

Concatenation means joining strings together using the + operator. You can also repeat a string using the * operator with a number, which is useful for creating patterns or repeated elements. These operations create new strings without modifying the original ones.

# Concatenation (joining strings)
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name

greeting = "Hello, " + first_name + "!"

# Repetition
star_line = "*" * 10             # "**********"
pattern = "Ha" * 3               # "HaHaHa"
dashes = "-" * 5 + " Section " + "-" * 5

print(full_name)                 # Output: John Doe
print(greeting)                  # Output: Hello, John!
print(star_line)
print(pattern)
print(dashes)

🔧 Essential String Methods

Methods are built-in actions you can perform on strings. Common methods include upper() (convert to uppercase), lower() (convert to lowercase), and len() (get length). Methods are called using dot notation: string.method(). These make it easy to transform and analyze text without writing complex code.

# String methods
text = "Hello, World!"

# Convert case
upper_text = text.upper()        # "HELLO, WORLD!"
lower_text = text.lower()        # "hello, world!"

# Get length (number of characters)
length = len(text)               # 13

# Check if string contains text
contains_hello = "Hello" in text  # True

# Replace text
new_text = text.replace("World", "Python")  # "Hello, Python!"

# Get specific character by position (indexing)
first_char = text[0]             # 'H'
last_char = text[-1]             # '!'

print(f"Upper: {upper_text}")
print(f"Lower: {lower_text}")
print(f"Length: {length}")
print(f"Replaced: {new_text}")

📍 String Indexing and Slicing

Strings are sequences of characters, and each character has a position called an index. Indexing starts at 0 for the first character, and you can use negative indices to count from the end (-1 is the last character). Slicing lets you extract parts of a string using [start:end] notation.

text = "Python"

# Indexing (getting single characters)
print(text[0])       # 'P' (first character)
print(text[1])       # 'y'
print(text[-1])      # 'n' (last character)
print(text[-2])      # 'o' (second from last)

# Slicing (getting parts of strings)
print(text[0:2])     # 'Py' (characters at positions 0 and 1)
print(text[2:4])     # 'th' (characters at positions 2 and 3)
print(text[:3])      # 'Pyt' (from start to position 3)
print(text[3:])      # 'hon' (from position 3 to end)
print(text[::2])     # 'Pto' (every 2nd character)

💡 Real-World Examples

Format a Full Name

first = "Sarah"
middle = "Marie"
last = "Johnson"

full_name = first + " " + middle + " " + last
print(f"Name: {full_name}")
print(f"Length: {len(full_name)} characters")
print(f"Initials: {first[0]}{middle[0]}{last[0]}")

Process User Input

user_input = "  Hello World  "

# Clean and process
cleaned = user_input.strip()     # Remove spaces
lowercase = cleaned.lower()      # Convert to lowercase
is_greeting = "hello" in lowercase  # Check if greeting

print(f"Cleaned: '{cleaned}'")
print(f"Lowercase: '{lowercase}'")
print(f"Is greeting: {is_greeting}")

Extract Information

email = "alice@example.com"

# Get username (before @)
username = email.split("@")[0]   # "alice"
# Get domain (after @)
domain = email.split("@")[1]     # "example.com"

print(f"Username: {username}")
print(f"Domain: {domain}")

✅ Key Takeaways

ConceptRemember
StringText enclosed in quotes
Single/Double QuotesBoth work, just match them
Concatenation+ joins strings together
Repetition* repeats a string
len()Gets number of characters
upper()Converts to UPPERCASE
lower()Converts to lowercase
IndexingGet single char: text[0]
SlicingGet part: text[0:3]
inCheck if substring exists

🔗 What's Next?

Strings are powerful, but formatting them nicely for output is crucial. Let's learn string formatting with modern f-strings!

Next: String Formatting →


Ready to practice? Try challenges or take the quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn