Working with Strings in Python

Strings are sequences of characters enclosed in quotes. Python provides powerful built-in functions and methods to manipulate strings efficiently.


1. Creating Strings

A string can be created using single, double, or triple quotes.

Example:

str1 = 'Hello'
str2 = "World"
str3 = '''Python is fun!'''
print(str1, str2, str3)

Output:

Hello World Python is fun!

2. Accessing Characters in a String

Strings are indexed, starting from 0.

Example:

text = "Python"
print(text[0])  # First character
print(text[-1]) # Last character

Output:

P
n

3. String Slicing

Extract a substring using slicing.

Syntax:

string[start:end:step]

Example:

text = "Hello, Python!"
print(text[0:5])   # Output: Hello
print(text[7:])    # Output: Python!
print(text[::-1])  # Output: !nohtyP ,olleH (Reversed String)

4. String Concatenation and Repetition

Example:

first = "Hello"
second = "World"
result = first + " " + second  # Concatenation
print(result)
print(result * 3)  # Repetition

Output:

Hello World
Hello WorldHello WorldHello World

5. String Methods

Python provides built-in methods to manipulate strings.

Example:

text = "python programming"
print(text.upper())   # Convert to uppercase
print(text.lower())   # Convert to lowercase
print(text.title())   # Convert to title case
print(text.replace("python", "Java"))  # Replace words
print(text.strip())   # Remove leading/trailing spaces

6. Checking Substrings

Example:

text = "Learning Python is fun!"
print("Python" in text)  # Output: True
print("Java" not in text)  # Output: True

7. Splitting and Joining Strings

Example:

sentence = "Python is easy to learn"
words = sentence.split()  # Split into words
print(words)

joined = "-".join(words)  # Join words with '-'
print(joined)

Output:

['Python', 'is', 'easy', 'to', 'learn']
Python-is-easy-to-learn

8. String Formatting

Python provides multiple ways to format strings.

Using f-strings (Recommended)

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

Using format() method

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

9. Escape Sequences

Escape sequences are used for special characters.

Example:

print("Hello\nWorld")  # New line
print("She said \"Python is fun!\"")  # Double quotes inside string

Summary

Strings are sequences of characters enclosed in quotes.
Indexing and slicing help access substrings.
String methods allow modification, searching, and formatting.
f-strings are the best way to format strings.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top