Wednesday, January 8, 2025
HomeProgrammingPython String Formatting - How to format String?

Python String Formatting – How to format String?

Python provides several ways to format strings, allowing you to insert variables and control the output format.

1. % Operator: Uses placeholders like %s for strings, %d for integers.

name = “Alice”
age = 30
formatted = “Name: %s, Age: %d” % (name, age)

See also  Serialization and Deserialization in Java with Example

2. str.format() Method: Uses curly braces {} as placeholders.

formatted = “Name: {}, Age: {}”.format(name, age)

3. F-strings (Python 3.6+): Embeds expressions inside curly braces prefixed by f.

formatted = f”Name: {name}, Age: {age}”

4. Template Strings: Offers simple substitutions, used with string.Template.

See also  Search a node in Binary Tree

from string import Template
template = Template(“Name: $name, Age: $age”)
formatted = template.substitute(name=name, age=age)

Each method offers flexibility depending on the use case, with f-strings being the most concise and readable.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x