Header Ads Widget

Ticker

6/random

Python String Formatting

Python String Formatting


String formatting in Python allows you to create dynamic strings by embedding variables or expressions within them. 


There are several ways to achieve string formatting, but the most common methods are using the `%` operator and the `format()` method.


Using `%` Operator:

```python

name = "Alice"

age = 25

height = 5.8


Old-style formatting

message = "Hello, my name is %s, I'm %d years old, and I'm %.2f feet tall." % (name, age, height)

print(message)

```


Using `format()` Method:

```python

name = "Bob"

age = 30

height = 6.1


New-style formatting

message = "Hello, my name is {}, I'm {} years old, and I'm {:.2f} feet tall.".format(name, age, height)

print(message)

```


f-strings (Python 3.6+):

```python

name = "Charlie"

age = 22

height = 5.5


# f-string

message = f"Hello, my name is {name}, I'm {age} years old, and I'm {height:.2f} feet tall."

print(message)

```


These examples showcase different ways to format strings in Python. The `%` operator uses placeholders like `%s` for strings, `%d` for integers, and `%f` for floating-point numbers. The `format()` method uses curly braces `{}` as placeholders, and f-strings directly embed expressions within curly braces, making the syntax concise and readable.

Post a Comment

0 Comments