techmore.in

Python - String Handling

1. What is String Handling?

String handling refers to the manipulation and processing of strings in Python. Strings are sequences of characters used to store text. Python provides several built-in methods and tools to work with strings effectively.

2. String Methods

Python provides a rich set of string methods to perform various operations such as searching, replacing, formatting, and case conversions.

python
text = "  hello world!  "
print(text.strip())  # Remove whitespace
print(text.upper())  # Uppercase
print(text.replace("world", "Python"))

3. f-strings

f-strings (formatted string literals) provide a way to embed expressions inside string literals using curly braces {} and prefixing the string with an f.

python
name = "Alice"
age = 25
print(f"Hello, my name is {name} and I am {age} years old.")

4. Slicing and Indexing

Python allows you to access parts of a string using indexing and slicing. Indexing starts at 0, and slicing uses the format [start:end].

python
message = "Python"
print(message[0])     # Output: P
print(message[1:4])   # Output: yth
print(message[-1])    # Output: n

5. Regular Expressions (re module)

Python's re module allows for advanced string matching and pattern recognition using regular expressions.

python
import re

pattern = r"\d{3}-\d{2}-\d{4}"
text = "My SSN is 123-45-6789."
match = re.search(pattern, text)
if match:
    print("Found:", match.group())

Conclusion

String handling is essential in almost every Python program. With powerful features like built-in methods, slicing, f-strings, and regular expressions, you can handle and manipulate text efficiently.