Python Strings: Basics and Advanced Formatting

🐍 Python Strings: Basics and Advanced Formatting

In Python, a string is a sequence of characters enclosed in quotes. Strings are one of the most commonly used data types and are immutable, meaning once created, they cannot be changed.


🔹 Basics of Strings

✅ Creating Strings

python

Copy

Edit

name = "Alice"

greeting = 'Hello'

sentence = """This is a 

multi-line string."""

✅ String Operations

python

Copy

Edit

# Concatenation

full = "Hello" + " " + "World"


# Repetition

echo = "Hi! " * 3  # Output: 'Hi! Hi! Hi! '


# Length

length = len("Python")  # 6


# Indexing

word = "Python"

first_letter = word[0]  # 'P'

last_letter = word[-1]  # 'n'


# Slicing

part = word[1:4]  # 'yth'

✅ String Methods

python

Copy

Edit

text = "  hello world  "

print(text.strip())      # Removes leading/trailing spaces

print(text.upper())      # '  HELLO WORLD  '

print(text.lower())      # '  hello world  '

print(text.replace("hello", "hi"))  # '  hi world  '

print("world" in text)   # True

🔹 Advanced String Formatting

Python provides several ways to format strings:


1. f-strings (Python 3.6+) — Most Recommended

python

Copy

Edit

name = "Alice"

age = 30

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

You can also add expressions inside:


python

Copy

Edit

print(f"Next year, I will be {age + 1}.")

2. str.format() Method

python

Copy

Edit

name = "Bob"

age = 25

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

With placeholders:


python

Copy

Edit

print("Name: {0}, Age: {1}".format(name, age))

print("Age: {age}, Name: {name}".format(name="Luna", age=22))

3. % Formatting (Old Style)

python

Copy

Edit

name = "Chris"

age = 40

print("My name is %s and I am %d years old." % (name, age))

🔹 Formatting Numbers and Strings

python

Copy

Edit

price = 19.99

print(f"Price: ${price:.2f}")     # 2 decimal places


num = 1234

print(f"Number with commas: {num:,}")  # Output: '1,234'

Padding and alignment:


python

Copy

Edit

text = "cat"

print(f"{text:>10}")  # Right-align in 10 spaces

print(f"{text:<10}")  # Left-align

print(f"{text:^10}")  # Center

🔹 Useful String Tricks

python

Copy

Edit

# Join

words = ['Python', 'is', 'fun']

sentence = " ".join(words)  # 'Python is fun'


# Split

text = "one,two,three"

parts = text.split(',')  # ['one', 'two', 'three']


# Check start/end

url = "https://openai.com"

print(url.startswith("https"))  # True

print(url.endswith(".com"))     # True

🔚 Conclusion

Strings in Python are powerful and flexible. From simple operations like concatenation to advanced formatting with f-strings and format(), Python gives you all the tools you need for working with text.

Learn Python Course in Hyderabad

Read More

Understanding Python Indentation and Code Blocks

What is %a in Python's string formatting (Python, string formatting, development)?

Visit Our Quality Thought Training in Hyderabad

Get Directions


Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Why Data Science Course?

How To Do Medical Coding Course?