StudyLover
  • Home
  • Study Zone
  • Profiles
  • Contact us
  • Sign in
StudyLover String Formatting
Download
  1. Python
  2. Text Processing with Python
String Concatenation : Assigning Strings
Text Processing with Python

String Formatting

String formatting allows you to create strings with embedded values in a controlled and readable manner. Python offers several methods for string formatting:

1. Old-style String Formatting (using %)

This method is older but still supported:

Python

name = "Alice"

age = 30

formatted_string = "Hello, %s! You are %d years old." % (name, age)

print(formatted_string)  # Output: Hello, Alice! You are 30 years old.

·         %s is a placeholder for a string.

·         %d is a placeholder for an integer.

·         The % operator is used to substitute values into the string.

2. Format Method (.format())

This method is more versatile and readable:

Python

name = "Bob"

price = 9.99

formatted_string = "Hello, {}! The price is {:.2f}".format(name, price)

print(formatted_string)  # Output: Hello, Bob! The price is 9.99

·         {} are placeholders for values.

·         .2f specifies a floating-point number with two decimal places.

3. f-strings (Formatted String Literals)

Introduced in Python 3.6, f-strings provide a cleaner and more concise way to format strings:

Python

name = "Charlie"

item = "apple"

quantity = 5

formatted_string = f"Hello, {name}! You bought {quantity} {item}s."

print(formatted_string)  # Output: Hello, Charlie! You bought 5 apples.

·         f before the string indicates an f-string.

·         Expressions within curly braces {} are evaluated and inserted into the string.

Key Points

·         Choose the method that best suits your needs based on readability and complexity.

·         f-strings are generally preferred for their simplicity and efficiency.

·         Use format specifiers (e.g., :.2f) for precise formatting of numbers.

 

String Concatenation Assigning Strings
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website