0% found this document useful (0 votes)
5 views5 pages

Strings and Multiline Strings

The document provides a comprehensive overview of string manipulation in Python, covering key concepts such as string properties, operations, methods, formatting, escape characters, and multiline strings. It includes examples and common mistakes to avoid, as well as real-world applications and practice exercises. Key takeaways emphasize the use of f-strings for formatting, the importance of escape characters, and the immutability of strings.

Uploaded by

Mercy Okanlawon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

Strings and Multiline Strings

The document provides a comprehensive overview of string manipulation in Python, covering key concepts such as string properties, operations, methods, formatting, escape characters, and multiline strings. It includes examples and common mistakes to avoid, as well as real-world applications and practice exercises. Key takeaways emphasize the use of f-strings for formatting, the importance of escape characters, and the immutability of strings.

Uploaded by

Mercy Okanlawon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Strings and Multiline Strings

Goal: Master string manipulation, formatting, escape characters, and


multiline strings in Python.

1. What Are Strings?

 Strings are sequences of characters enclosed in quotes ( ' ', "


", ''' ''', or """ """).

 Examples:
name = "Alice"
message = 'Hello, world!'
address = '''123 Main Street
New York, NY'''

Key Properties:

 Immutable: Once created, individual characters cannot be


modified.
 Indexable: Access characters using indices (e.g., name[0] → 'A').
 Iterable: Loop through characters using for loops.

2. String Operations

1. Concatenation: Combine strings with +.


first = "Hello"
second = "World"
full = first + ", " + second + "!"
print(full) # Output: "Hello, World!"

2. Repetition: Repeat strings with *.


line = "-" * 40
print(line) # Output: "----------------------------------------"

3. Slicing: Extract substrings using [start:end].


text = "Python"
print(text[1:4]) # Output: "yth"

3. String Methods

Common methods for manipulating strings:

Method Description Example

.upper() Converts to uppercase "hello".upper() → "HELLO"

.lower() Converts to lowercase "HELLO".lower() → "hello"

.strip() Removes whitespace from edges " hi ".strip() → "hi"

"a,b,c".split(",") →
.split() Splits into a list of substrings ["a","b","c"]

.find()
Returns the first index of a "apple".find("p") → 1
substring

.replace()
Replaces a substring with "hello".replace("e", "a") →
another "hallo"

Important Notes:

 .find() vs .index():

o .find() returns -1 if the substring is missing.

o .index() raises a ValueError if the substring is missing.


print("hello".find("z")) # Output: -1
print("hello".index("z")) # Raises ValueError

4. String Formatting

1. f-strings (Python 3.6+): Embed variables/expressions directly.


name = "Alice"
age = 30
print(f"{name} is {age} years old.") # Output: "Alice is 30 years
old."

2. Formatting Numbers:

o Round to 2 decimal places:


price = 3.2048
print(f"Price: ${price:.2f}") # Output: "Price: $3.20"

3. Alignment:
print(f"{'Left':<10}") # Left-aligned: "Left "
print(f"{'Right':>10}") # Right-aligned: " Right"

5. Escape Characters

Special characters starting with \:

Escap
Meaning Example
e

\n Newline "Line1\nLine2"

\t Tab "Hello\tWorld"

\\ Backslash "C:\\Users"

\" Double quote "He said \"Hi\"."

Example:

print("Hello\nWorld")
# Output:
# Hello
# World

6. Multiline Strings
Use triple quotes (''' or """) for multiline strings:

poem = """Roses are red,


Violets are blue,
Sugar is sweet,
And so are you."""
print(poem)

Use Cases:

 Preserve line breaks in text.


 Write formatted text (e.g., JSON, HTML).

7. Common Mistakes

1. Forgetting Quotes:
message = Hello # SyntaxError: Missing quotes.

2. Mismatched Quotes:
text = 'He said "Wow!' # Missing closing quote.

3. Unescaped Quotes:
text = "She said "Hello"" # Error: Use \" or different quotes.

4. Useless f-strings:
print(f"Hello") # Works but unnecessary (no variables embedded).

8. Real-World Applications

1. User Input Sanitization:


user_input = input("Enter a username: ").strip().lower()

2. File Path Handling:


path = r"C:\Users\Alice\Documents" # Raw string (ignores escapes).

3. Generating Reports:
header = "Name".ljust(15) + "Age".rjust(5)
print(header) # Output: "Name Age"
9. Practice Examples

1. Remove All Spaces:


sentence = "Hello World"
no_spaces = sentence.replace(" ", "")
print(no_spaces) # Output: "HelloWorld"

2. Check for Substring:


email = "[email protected]"
if "@" in email and "." in email:
print("Valid email format!")

3. Reverse a String:
text = "Python"
reversed_text = text[::-1]
print(reversed_text) # Output: "nohtyP"

Key Takeaways

1. Use f"{var:.2f}" to format numbers.


2. Escape characters like \n and \" handle special cases.
3. Triple quotes preserve multiline formatting.
4. Strings are immutable—operations return new strings.

You might also like