Youโ€™re the Expert!

pynfinity

Build mountain with each pebble ๐Ÿง—

Topics | Stepping Stones
Official Guides
Community Contributions
๐Ÿ“–
Guides
In-depth topic walkthroughs with examples
19 topics
โšก
Bytes
Detailed notes, tutorials & code deep-dives
83 posts
๐Ÿ’Ž
Bits
Quick code snippets โ€” read in one scroll
42 snippets
๐Ÿ“–

Official Guides

โšก

Bytes โ€” Tutorials & Deep-Dives

๐Ÿงฉ
๐Ÿงฉ Regular Expressions
Regular expressions are a powerful tool for various kinds of string manipulation.
pynfinity 2027-06-23
โณ
โณ Time Series Resampling
Resampling allows you to change the frequency of your time series data, e.g., from daily to monthly.
santoshtvk 2028-01-09
๐ŸŽ›๏ธ
๐ŸŽ›๏ธ Multiprocessing
Multiprocessing allows you to create processes, which can run in parallel on multiple CPU cores.
pynfinity 2025-01-23
๐Ÿณ
๐Ÿณ Dockerfiles
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.
pynfinity 2023-10-31
๐Ÿ“ธ
๐Ÿ“ธ OpenCV Image Reading
OpenCV is a huge open-source library for computer vision, machine learning, and image processing.
pynfinity 2025-05-02
โณ
โณ Time Series Resampling
Resampling allows you to change the frequency of your time series data, e.g., from daily to monthly.
santoshtvk 2026-01-01
๐Ÿ“„
๐Ÿ“„ JSON Handling
JSON is a lightweight data interchange format inspired by JavaScript object literal syntax.
pynfinity 2024-09-15
โšก
โšก Python async/await โ€” Asynchronous Programming Guide
asyncio enables concurrent I/O-bound tasks in Python without threads. Learn async/await to write high-performance APIs and web scrapers.
santoshtvk 2025-12-02
โ™พ๏ธ
โ™พ๏ธ Python Generators โ€” Memory-Efficient Iterators
Generators produce values on demand instead of storing everything in memory. Perfect for large datasets, streaming, and infinite sequences.
santoshtvk 2026-09-01
๐Ÿ”
๐Ÿ” Python Environment Variables โ€” Managing Config Safely
Never hardcode secrets in Python code. Environment variables and .env files keep API keys, passwords, and configs out of source code.
santoshtvk 2026-05-15
๐Ÿ“š
๐Ÿ“š Collections Module
This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers.
pynfinity 2023-04-17
๐Ÿšช
๐Ÿšช Context Managers
Context managers allow you to allocate and release resources precisely when you want to.
pynfinity 2023-05-13
โšก
โšก FastAPI Endpoints
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+.
pynfinity 2023-12-24
๐Ÿผ
๐Ÿผ Pandas DataFrames
Pandas DataFrame is a primary two-dimensional tabular data structure in the pandas Python library. They allow you to store and manipulate tabular data efficiently.
santoshtvk 2025-07-01
๐Ÿท๏ธ
๐Ÿท๏ธ Type Hinting
Type hinting helps you document your code and catch errors early.
santoshtvk 2028-01-29
โœ๏ธ
โœ๏ธ Python f-Strings โ€” The Modern Way to Format Strings
f-strings (formatted string literals) are the fastest, most readable way to format strings in Python 3.6+. Master them completely.
santoshtvk 2026-07-14
๐Ÿ“ฆ
๐Ÿ“ฆ Dataclasses
Dataclasses provide a decorator and functions for automatically adding generated special methods to classes.
pynfinity 2023-08-19
๐Ÿ–ฅ๏ธ
๐Ÿ–ฅ๏ธ Python argparse โ€” Building Command-Line Tools
argparse turns Python scripts into professional CLI tools with automatic help messages, type validation, and optional/required arguments.
santoshtvk 2025-11-21
๐Ÿ“Š
๐Ÿ“Š Python dataclasses โ€” Clean Data Models in Python
The @dataclass decorator auto-generates boilerplate code for data-holding classes โ€” __init__, __repr__, __eq__ all for free.
santoshtvk 2026-02-06
๐Ÿ“ง
๐Ÿ“ง How to Send Email with Python
Python makes sending emails straightforward using the smtplib module. Learn to send plain text, HTML emails, and attachments.
santoshtvk 2024-06-12
๐Ÿ–ฅ๏ธ
๐Ÿ–ฅ๏ธ OS Module
The os module provides a portable way of using operating system dependent functionality.
santoshtvk 2025-05-27
๐Ÿ“‚
๐Ÿ“‚ How to Read a CSV File in Python
Reading CSV files is one of the most common tasks in Python. The built-in csv module and pandas both make it simple.
santoshtvk 2024-05-23
๐Ÿ•ธ๏ธ
๐Ÿ•ธ๏ธ NetworkX Graphs
NetworkX is a Python package for the creation, manipulation, and study of the structure of complex networks.
pynfinity 2025-03-06
๐Ÿ•ท๏ธ
๐Ÿ•ท๏ธ Python Web Scraping with Selenium โ€” Dynamic Sites
Selenium controls a real browser for scraping JavaScript-heavy sites that BeautifulSoup can't handle. Automate login, fill forms, click buttons.
santoshtvk 2027-05-16
โœจ
โœจ Jupyter Magic Commands
Magic commands are special commands that you can run in Jupyter notebooks to perform special tasks.
santoshtvk 2024-10-17
๐Ÿ“Š
๐Ÿ“Š Interactive Plots with Plotly
Plotly allows you to create interactive charts that you can zoom, pan, and hover over.
santoshtvk 2024-07-23
๐ŸŒฒ
๐ŸŒฒ Git Basics
Git is a distributed version control system for tracking changes in source code during software development.
pynfinity 2024-04-16
๐ŸŽ€
๐ŸŽ€ Decorators
Decorators allow you to modify the behavior of a function or class.
pynfinity 2023-09-24
๐Ÿ“
๐Ÿ“ Python File Handling โ€” Read, Write, and Append Files
Python file handling covers reading, writing, and appending data. The 'with' statement ensures files are always closed properly.
santoshtvk 2026-08-08
๐Ÿ”
๐Ÿ” Python Type Hints โ€” Write Safer, Self-Documenting Code
Type hints make Python code more readable, catch bugs earlier, and supercharge IDE autocomplete. Introduced in Python 3.5, improved in every version since.
santoshtvk 2027-05-05
๐Ÿชต
๐Ÿชต Logging
Logging is a means of tracking events that happen when some software runs.
santoshtvk 2024-12-03
โ˜๏ธ
โ˜๏ธ AWS S3 with Boto3
Boto3 is the Amazon Web Services (AWS) Software Development Kit (SDK) for Python.
santoshtvk 2023-03-18
๐Ÿ”ฅ
๐Ÿ”ฅ Seaborn Heatmaps
Seaborn makes it easy to create attractive heatmaps to visualize correlation matrices or 2D data.
santoshtvk 2027-08-28
โณ
โณ AsyncIO
AsyncIO is a library to write concurrent code using the async/await syntax.
santoshtvk 2023-02-23
โž—
โž— Math Module
This module provides access to the mathematical functions defined by the C standard.
pynfinity 2024-12-18
๐Ÿ“–
๐Ÿ“– Python Dictionary Methods โ€” Complete Guide
Python dictionaries are flexible key-value stores. Mastering dict methods unlocks faster, more readable data manipulation code.
santoshtvk 2026-04-15
๐Ÿ“ฆ
๐Ÿ“ฆ Virtual Environments
Virtual environments allow you to manage dependencies for different projects separately.
santoshtvk 2028-02-11
โšก
โšก Generators
Generators are a simple way of creating iterators. They use the `yield` statement.
pynfinity 2024-03-14
๐Ÿงต
๐Ÿงต Multithreading
Threading allows you to run multiple operations concurrently in a single process.
pynfinity 2025-02-09
๐Ÿ“‰
๐Ÿ“‰ Statsmodels OLS
Statsmodels allows you to explore data, estimate statistical models, and perform statistical tests.
santoshtvk 2027-10-18
โš™๏ธ
โš™๏ธ Sys Module
The sys module provides access to some variables used or maintained by the interpreter.
santoshtvk 2027-11-21
๐Ÿ—บ๏ธ
๐Ÿ—บ๏ธ Folium Maps
Folium builds on the data wrangling strengths of the Python ecosystem and the mapping strengths of the Leaflet.js library.
pynfinity 2024-01-31
๐Ÿงน
๐Ÿงน Data Cleaning with Dropna
Missing data is a common problem. Pandas provides `dropna()` to easily remove rows or columns with null values.
santoshtvk 2026-01-01
๐Ÿ›ก๏ธ
๐Ÿ›ก๏ธ Pydantic Models
Pydantic performs data validation and settings management using Python type annotations.
pynfinity 2025-09-10
๐ŸŽ
๐ŸŽ Python Decorators Explained with Examples
Decorators are one of Python's most elegant features. They wrap functions to add extra behaviour โ€” without changing the original function code.
santoshtvk 2026-03-19
๐Ÿงช
๐Ÿงช Python Testing with unittest and pytest
Testing your Python code prevents bugs from reaching production. pytest makes writing and running tests fast, readable, and enjoyable.
santoshtvk 2027-04-01
๐Ÿค–
๐Ÿค– Scikit-Learn Linear Regression
Linear Regression is the 'Hello World' of Machine Learning. Scikit-Learn makes it a breeze to implement.
pynfinity 2026-01-01
๐Ÿ”ฎ
๐Ÿ”ฎ Python Sets โ€” The Underrated Power of Set Operations
Python sets are unordered collections of unique elements. Set operations like union, intersection, and difference are lightning fast.
santoshtvk 2027-03-01
๐Ÿ”ข
๐Ÿ”ข NumPy Arrays
NumPy arrays are faster and more compact than Python lists. They are the foundation for scientific computing.
pynfinity 2025-04-18
๐Ÿ“œ
๐Ÿ“œ List Comprehensions
List comprehensions provide a concise way to create lists.
santoshtvk 2024-11-17
๐Ÿ”
๐Ÿ” Exploratory Data Analysis (EDA)
EDA is crucial for understanding your data. The `describe()` method gives you a quick statistical summary.
santoshtvk 2023-11-21
๐Ÿงฉ
๐Ÿงฉ Python Regex Tutorial with Examples
Regular expressions (regex) in Python use the re module to search, match, and manipulate strings with powerful pattern rules.
santoshtvk 2027-01-29
๐Ÿ“‰
๐Ÿ“‰ Matplotlib Plotting
Matplotlib is the grandfather of Python visualization libraries. It gives you control over every aspect of a figure.
santoshtvk 2025-01-11
๐ŸŽฏ
๐ŸŽฏ Python Common Interview Questions and Answers
Top Python interview questions asked at MNCs, and startups โ€” with clear answers and code examples.
santoshtvk 2025-12-18
๐Ÿš€
๐Ÿš€ Streamlit Apps
Streamlit turns data scripts into shareable web apps in minutes. All in pure Python.
pynfinity 2027-11-01
ฮป
ฮป Python Lambda Functions โ€” Small Anonymous Functions
Lambda functions are compact, one-line anonymous functions. Perfect for short operations passed to sort(), filter(), and map().
santoshtvk 2026-10-06
๐Ÿ“…
๐Ÿ“… Python datetime Module โ€” Working with Dates and Times
Python's datetime module handles dates, times, timezones, and arithmetic. Essential for logs, scheduling, and data pipelines.
santoshtvk 2026-02-20
โœจ
โœจ Jupyter Magic Commands
Magic commands are special commands that you can run in Jupyter notebooks to perform special tasks.
santoshtvk 2026-01-01
๐Ÿ—„๏ธ
๐Ÿ—„๏ธ SQLAlchemy Basics
SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power of SQL.
pynfinity 2027-09-12
๐Ÿ› ๏ธ
๐Ÿ› ๏ธ Functools
The functools module is for higher-order functions: functions that act on or return other functions.
pynfinity 2024-02-20
๐Ÿšช
๐Ÿšช Python Context Managers โ€” The with Statement Explained
Context managers ensure resources (files, DB connections, locks) are always properly cleaned up, even when exceptions occur.
santoshtvk 2026-01-04
๐Ÿงน
๐Ÿงน Data Cleaning with Dropna
Missing data is a common problem. Pandas provides `dropna()` to easily remove rows or columns with null values.
santoshtvk 2023-07-17
๐ŸŒ
๐ŸŒ How to Use the requests Library in Python
The requests library is the go-to tool for making HTTP requests in Python. GET data from APIs, POST forms, handle auth โ€” all in a few lines.
santoshtvk 2024-07-02
๐Ÿ•ธ๏ธ
๐Ÿ•ธ๏ธ Web Scraping with BeautifulSoup
BeautifulSoup helps you parse HTML and extract the data you need from websites.
pynfinity 2028-03-12
๐Ÿ•ธ๏ธ
๐Ÿ•ธ๏ธ Web Scraping with BeautifulSoup
BeautifulSoup helps you parse HTML and extract the data you need from websites.
pynfinity 2026-01-01
๐Ÿ“Š
๐Ÿ“Š Interactive Plots with Plotly
Plotly allows you to create interactive charts that you can zoom, pan, and hover over.
santoshtvk 2026-01-01
๐Ÿ“
๐Ÿ“ Python logging Module โ€” Proper Application Logging
Real applications need structured logs, not print() statements. Python's logging module provides levels, formatting, and file logging.
santoshtvk 2026-12-11
๐Ÿ”
๐Ÿ” Itertools
This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML.
santoshtvk 2024-08-17
๐Ÿ”„
๐Ÿ”„ Python enumerate() and zip() โ€” Cleaner Loop Patterns
enumerate() adds automatic counters to loops; zip() iterates multiple sequences together. Both eliminate messy manual indexing.
santoshtvk 2026-05-05
๐Ÿฅ’
๐Ÿฅ’ Pickle Serialization
The pickle module implements binary protocols for serializing and de-serializing a Python object structure.
pynfinity 2025-08-07
ฮป
ฮป Lambda Functions
A lambda function is a small anonymous function. It can take any number of arguments, but can only have one expression.
santoshtvk 2028-03-25
๐Ÿ—๏ธ
๐Ÿ—๏ธ Python OOP โ€” Classes, Objects, and Inheritance
Object-Oriented Programming in Python uses classes to bundle data and behaviour together. Master classes, inheritance, and dunder methods.
santoshtvk 2026-12-26
๐Ÿค–
๐Ÿค– Scikit-Learn Linear Regression
Linear Regression is the 'Hello World' of Machine Learning. Scikit-Learn makes it a breeze to implement.
pynfinity 2027-07-19
โš”๏ธ
โš”๏ธ FastAPI vs Flask โ€” Which Should You Choose?
FastAPI and Flask are two of Python's most popular web frameworks. Here's a clear side-by-side comparison with real code examples.
santoshtvk 2024-01-15
๐Ÿ“
๐Ÿ“ NLTK Tokenization
Tokenization is the first step in NLP. It breaks text down into words or sentences.
santoshtvk 2025-04-06
๐Ÿ“Š
๐Ÿ“Š CSV Processing
The csv module implements classes to read and write tabular data in CSV format.
santoshtvk 2023-06-14
๐Ÿง 
๐Ÿง  TensorFlow Basics
TensorFlow is a powerful library for numerical computation and large-scale machine learning.
santoshtvk 2027-12-16
๐Ÿ”ฅ
๐Ÿ”ฅ PyTorch Tensors
PyTorch tensors are similar to NumPy arrays but can run on GPUs for accelerated computing.
pynfinity 2027-06-12
๐Ÿ’ป
๐Ÿ’ป Argparse CLI
The argparse module makes it easy to write user-friendly command-line interfaces.
santoshtvk 2023-02-04
๐Ÿงช
๐Ÿงช Pytest Testing
Pytest is a framework that makes building simple and scalable tests easy.
santoshtvk 2025-10-19
๐Ÿ”
๐Ÿ” Exploratory Data Analysis (EDA)
EDA is crucial for understanding your data. The `describe()` method gives you a quick statistical summary.
santoshtvk 2026-01-01
โšก
โšก Python List Comprehension Examples
List comprehensions are Python's elegant one-liner loops. Write cleaner, faster code with this powerful feature.
santoshtvk 2026-11-12
๐Ÿ›ก๏ธ
๐Ÿ›ก๏ธ Python Error Handling โ€” try, except, finally Explained
Proper exception handling makes your Python code robust and production-ready. Learn try/except/finally with real-world patterns.
santoshtvk 2026-06-14
โœ๏ธ
Write a New Post
๐Ÿ’Ž

Bits โ€” Quick Code Snippets

๐Ÿ—บ๏ธ Folium Maps
๐Ÿ—บ๏ธ Folium Maps
๐Ÿ“ฆ Dataclasses
๐Ÿ“ฆ Dataclasses
๐Ÿ” Itertools
๐Ÿ” Itertools
๐Ÿ—„๏ธ SQLAlchemy Basics
๐Ÿ—„๏ธ SQLAlchemy Basics
๐Ÿ“„ JSON Handling
๐Ÿ“„ JSON Handling
๐Ÿ–ฅ๏ธ OS Module
๐Ÿ–ฅ๏ธ OS Module
๐Ÿ”ข NumPy Arrays
๐Ÿ”ข NumPy Arrays
โšก Generators
โšก Generators
๐Ÿผ Pandas DataFrames
๐Ÿผ Pandas DataFrames
๐ŸŽ›๏ธ Multiprocessing
๐ŸŽ›๏ธ Multiprocessing
โšก FastAPI Endpoints
โšก FastAPI Endpoints
๐Ÿ“œ List Comprehensions
๐Ÿ“œ List Comprehensions
๐Ÿชต Logging
๐Ÿชต Logging
๐Ÿš€ Streamlit Apps
๐Ÿš€ Streamlit Apps
๐Ÿงช Pytest Testing
๐Ÿงช Pytest Testing
๐Ÿง  TensorFlow Basics
๐Ÿง  TensorFlow Basics
๐ŸŒฒ Git Basics
๐ŸŒฒ Git Basics
๐Ÿ“ฆ Virtual Environments
๐Ÿ“ฆ Virtual Environments
๐Ÿท๏ธ Type Hinting
๐Ÿท๏ธ Type Hinting
๐Ÿšช Context Managers
๐Ÿšช Context Managers
๐Ÿ› ๏ธ Functools
๐Ÿ› ๏ธ Functools
๐Ÿงฉ Regular Expressions
๐Ÿงฉ Regular Expressions
๐ŸŽ€ Decorators
๐ŸŽ€ Decorators
๐Ÿ“ธ OpenCV Image Reading
๐Ÿ“ธ OpenCV Image Reading
๐Ÿ’ป Argparse CLI
๐Ÿ’ป Argparse CLI
๐Ÿ›ก๏ธ Pydantic Models
๐Ÿ›ก๏ธ Pydantic Models
๐Ÿ“š Collections Module
๐Ÿ“š Collections Module
๐Ÿ“ NLTK Tokenization
๐Ÿ“ NLTK Tokenization
๐Ÿ“‰ Matplotlib Plotting
๐Ÿ“‰ Matplotlib Plotting
๐Ÿ”ฅ Seaborn Heatmaps
๐Ÿ”ฅ Seaborn Heatmaps
๐Ÿงต Multithreading
๐Ÿงต Multithreading
โณ AsyncIO
โณ AsyncIO
๐Ÿ”ฅ PyTorch Tensors
๐Ÿ”ฅ PyTorch Tensors
โš™๏ธ Sys Module
โš™๏ธ Sys Module
โ˜๏ธ AWS S3 with Boto3
โ˜๏ธ AWS S3 with Boto3
๐Ÿฅ’ Pickle Serialization
๐Ÿฅ’ Pickle Serialization
๐Ÿ•ธ๏ธ NetworkX Graphs
๐Ÿ•ธ๏ธ NetworkX Graphs
โž— Math Module
โž— Math Module
ฮป Lambda Functions
ฮป Lambda Functions
๐Ÿ“Š CSV Processing
๐Ÿ“Š CSV Processing
๐Ÿณ Dockerfiles
๐Ÿณ Dockerfiles
๐Ÿ“‰ Statsmodels OLS
๐Ÿ“‰ Statsmodels OLS
+ New Post

Python String Manipulation:

From Basics to Advanced Techniques: This pebble is designed to be your go-to resource for mastering string manipulation in Python. We'll start with the fundamentals and gradually explore more complex and lesser-known functions. Let's dive in!

1. The Basics: What are Strings?
In Python, a string is a sequence of characters enclosed in either single quotes ('...'), double quotes ("..."), or triple quotes ('''...''' or """..."""). Strings are immutable, which means that once a string is created, it cannot be changed. However, we can perform various operations to create new strings based on the original.

Creating Strings

# Single quotes
my_string1 = 'Hello, World!'

# Double quotes
my_string2 = "Python is fun."

# Triple quotes for multi-line strings
my_string3 = """This is a
multi-line
string."""

print(my_string1)
print(my_string2)
print(my_string3)

String Concatenation and Repetition

You can combine strings using the + operator and repeat them using the * operator.

first_name = "Santosh"
last_name = "V"

# Concatenation
full_name = first_name + " " + last_name
print(full_name)  # Output: Santosh V

# Repetition
separator = "-" * 10
print(separator)  

# Output: ----------

2. Formatting Strings with f-Strings, .format() and Specifiers
Properly formatting strings is crucial for creating readable output. Python offers several ways to do this.

F-Strings (Formatted String Literals)

This is the modern and preferred way.
You prefix the string with an f or F and place variables or expressions directly inside curly braces {}.

Basic F-String Usage

name = "Santosh"
age = 30

greeting = f"My name is {name} and I am {age} years old."
print(greeting)
# Output: My name is Santosh and I am 30 years old.

The .format() Method

Before f-strings, the .format() method was the standard.
It works by placing placeholder curly braces in the string and then calling the method with the values to insert.

name = "santosh"
age = 25

# Using positional arguments
greeting_pos = "My name is {} and I am {} years old.".format(name, age)
print(greeting_pos)

# Using keyword arguments
greeting_key = "My name is {name} and I am {age} years old.".format(name="Santosh", age=35)
print(greeting_key)

Name Specifiers for Advanced Formatting

F-strings also allow for "name specifiers" that give you more control over the formatting of the embedded expressions. The general syntax is {value:specifier}.

Alignment and Padding

You can align text to the left (<), right (>), or center (^) within a specified width.

text = "Python"

# Left-aligned, width of 20
print(f"'{text:<20}'")  # Output: 'Python              '

# Right-aligned, width of 20
print(f"'{text:>20}'")  # Output: '              Python'

# Centered, width of 20
print(f"'{text:^20}'")  # Output: '       Python       '

# You can also specify a fill character
print(f"'{text:*^20}'") # Output: '*******Python*******'

Number Formatting

F-strings are powerful for formatting numbers.

number = 1234.56789

# Limiting decimal places
print(f"Two decimal places: {number:.2f}")  # Output: 1234.57

# Adding a comma as thousands separator
print(f"With comma: {number:,.2f}")  # Output: 1,234.57

# Displaying as a percentage
percentage = 0.85
print(f"Percentage: {percentage:.1%}") # Output: 85.0%

3. Checking String Content: isdigit(), isnumeric(), and isdecimal()

These three methods help you check if a string consists of numeric characters, but they have subtle and important differences.

isdecimal()
This is the most restrictive method. It returns True only if all characters in the string are decimal characters (0-9).

s1 = "12345"
s2 = "123.45"
s3 = "\u00B2"  # Superscript two

print(f"'{s1}'.isdecimal(): {s1.isdecimal()}")  # Output: True
print(f"'{s2}'.isdecimal(): {s2.isdecimal()}")  # Output: False
print(f"'{s3}'.isdecimal(): {s3.isdecimal()}")  # Output: False

isdigit()
This method is broader than isdecimal(). It returns True if all characters are digits, which includes decimal characters and superscripts/subscripts.

s1 = "12345"
s2 = "\u00B2"  # Superscript two
s3 = "\u2153"  # Vulgar fraction one-third

print(f"'{s1}'.isdigit(): {s1.isdigit()}")  # Output: True
print(f"'{s2}'.isdigit(): {s2.isdigit()}")  # Output: True
print(f"'{s3}'.isdigit(): {s3.isdigit()}")  # Output: False

isnumeric()
This is the most general of the three. It returns True for digits, fractions, subscripts, superscripts, and other numeric characters in various languages.

s1 = "12345"
s2 = "\u00B2"  # Superscript two
s3 = "\u2153"  # Vulgar fraction one-third
s4 = "ไธ€ไบŒไธ‰" # Chinese numerals

print(f"'{s1}'.isnumeric(): {s1.isnumeric()}")  # Output: True
print(f"'{s2}'.isnumeric(): {s2.isnumeric()}")  # Output: True
print(f"'{s3}'.isnumeric(): {s3.isnumeric()}")  # Output: True
print(f"'{s4}'.isnumeric(): {s4.isnumeric()}")  # Output: True

Key Takeaway: Use isdecimal() when you need to be sure the string can be converted to an integer. isdigit() is useful for a broader range of digit-like characters. isnumeric() is the most inclusive.

isdigit() isnumeric() isdecimal()
True is all characters in string are digits (0-9) True if all the characters in the string are numeric True if all characters in string are decimals
Includes characters like superscript and other Unicode Includes digits, fractions, roman numerals and other numeric Unicode characters More restrictive than other 2, as it considers only standard base-10 digits

4. Finding and Counting Substrings

These functions help you locate and quantify characters or sequences of characters within a string.
find() and rfind()

find(substring): Returns the lowest index in the string where substring is found. If it's not found, it returns -1.

rfind(substring): Returns the highest index (searches from the right). Also returns -1 if not found.

sentence = "The quick brown fox jumps over the lazy dog."

# Find the first occurrence of "fox"
print(f'Index of "fox": {sentence.find("fox")}')  # Output: 16

# Find the first occurrence of "the" (case-sensitive)
print(f'Index of "the": {sentence.find("the")}')  # Output: 31

# Find the last occurrence of "the"
print(f'Index of "the" from the right: {sentence.rfind("the")}') # Output: 31

# What if the substring isn't there?
print(f'Index of "cat": {sentence.find("cat")}')  # Output: -1

index() and rindex()
These are nearly identical to find() and rfind(), with one critical difference:
if the substring is not found, they raise a ValueError instead of returning -1.

When to use find() vs index()?

Use find() if you just want to check for existence and get an index without worrying about errors. It's great for conditional checks (if my_string.find(...) != -1:).

Use index() if you expect the substring to be present and want the program to stop with an error if it's not. This can help catch unexpected data issues.

count()
Returns the number of non-overlapping occurrences of a substring.

sentence = "the three thieves thought that they could trick the other three."
print(f'The word "the" appears {sentence.count("the")} times.') # Output: 5

5. Modifying and Cleaning Strings

Since strings are immutable, these methods return a new, modified copy of the string.

Case Modification

upper(): Converts the entire string to uppercase.

lower(): Converts the entire string to lowercase.

capitalize(): Makes the first character uppercase and the rest lowercase.

title(): Capitalizes the first letter of each word.

swapcase(): Swaps the case of every letter (upper becomes lower, lower becomes upper).

casefold(): A more aggressive version of lower(), useful for caseless comparisons across different languages (e.g., German "รŸ" becomes "ss").

text = "weLCoMe to tHe jUnGle"
print(f"Original: {text}")
print(f"upper(): {text.upper()}")
print(f"lower(): {text.lower()}")
print(f"capitalize(): {text.capitalize()}")
print(f"title(): {text.title()}")
print(f"swapcase(): {text.swapcase()}")

Stripping Whitespace

strip(): Removes leading and trailing whitespace (spaces, tabs, newlines).

lstrip(): Removes leading (left) whitespace only.

rstrip(): Removes trailing (right) whitespace only.

You can also pass a string of characters to strip those specific characters instead of whitespace.

messy_string = "   \n  some text here   \t "
print(f"'{messy_string.strip()}'")   # Output: 'some text here'
print(f"'{messy_string.lstrip()}'")  # Output: 'some text here   \t '
print(f"'{messy_string.rstrip()}'")  # Output: '   \n  some text here'

# Stripping specific characters
path = "///documents/file.txt///"
print(path.strip('/')) # Output: documents/file.txt

replace()

Replaces all occurrences of a substring with another. You can also provide a third argument to limit the number of replacements.

sentence = "I like cats. Cats are cute."
new_sentence = sentence.replace("cats", "dogs")
print(new_sentence) # Output: I like dogs. Dogs are cute.

# Replace only the first occurrence
limited_replace = sentence.replace("Cats", "Dogs", 1)
print(limited_replace) # Output: I like cats. Dogs are cute.

6. Lesser-Known but Useful String Functions

Let's explore some string methods that are not as commonly taught but can be incredibly helpful.

casefold()
This method is a more aggressive version of lower(). It's designed for caseless string comparisons and can handle more Unicode characters.
For example, the German letter "รŸ" is equivalent to "ss".

german_string = "Der FluรŸ"

print(f"lower(): {german_string.lower()}")      # Output: der fluรŸ
print(f"casefold(): {german_string.casefold()}")  # Output: der fluss

expandtabs()
This method replaces tab characters (\t) with a specified number of spaces.

text = "Name:\tJohn\nAge:\t30"

print("Default tab size (8):")
print(text.expandtabs())

print("\nTab size of 15:")
print(text.expandtabs(15))

ljust(), rjust(), center()
We saw these in f-string formatting, but they are also available as string methods for padding a string with a specified character (default is a space) to a certain width.

text = "menu"

print(f"'{text.ljust(10, '-')}'") # Output: 'menu------'
print(f"'{text.rjust(10, '-')}'") # Output: '------menu'
print(f"'{text.center(10, '-')}'")# Output: '---menu---'

zfill()
This method pads a numeric string on the left with zeros. It's particularly useful for creating fixed-width numeric representations.

number_str = "42"

print(number_str.zfill(5))  # Output: 00042

negative_number_str = "-42"
print(negative_number_str.zfill(5)) # Output: -0042

partition() and rpartition()
These methods split a string into three parts based on a separator.

partition() finds the first occurrence of the separator,
rpartition() finds the last. They return a tuple containing the part before the separator, the separator itself, and the part after.

url = "https://www.example.com/path/to/file.txt"

# Partitioning from the left
print(url.partition("://"))
# Output: ('https', '://', 'www.example.com/path/to/file.txt')

# Partitioning from the right to get the filename
print(url.rpartition('/'))
# Output: ('https://www.example.com/path/to', '/', 'file.txt')

translate() and maketrans()
These two methods work together to perform complex character replacements.

str.maketrans() creates a translation table, and translate() applies it.

Simple Two-Argument maketrans()

This maps characters from the first string to the corresponding characters in the second string.

# Replace vowels with numbers
input_str = "hello world"
translation_table = str.maketrans("aeiou", "12345")
translated_str = input_str.translate(translation_table)
print(translated_str) # Output: h2ll4 w4rld

Three-Argument maketrans()

The third argument specifies characters to be removed.

# Remove punctuation
input_str = "This is a sentence."
translation_table = str.maketrans("", "", ".,")
translated_str = input_str.translate(translation_table)
print(translated_str) # Output: This is a sentence

encode()

This method returns an encoded version of the string as a bytes object. This is essential when dealing with files, network requests, or any situation where data needs to be represented as a sequence of bytes. The most common encoding is UTF-8.

text = "Hello, world! ๐Ÿ˜Š"

# Encode the string into bytes using UTF-8
encoded_text = text.encode('utf-8')

print(f"Original string: {text}")
print(f"Type of original: {type(text)}")
print(f"Encoded bytes: {encoded_text}")
print(f"Type of encoded: {type(encoded_text)}")

# To get it back, you would use .decode()
decoded_text = encoded_text.decode('utf-8')
print(f"Decoded string: {decoded_text}")

Created with โค๏ธ by Pynfinity



Pynfinity
Install Pynfinity Add to home screen for the best experience