String_Formating #138167
Unanswered
martinondiwa
asked this question in
Programming Help
String_Formating
#138167
Replies: 2 comments
-
|
Thanks ! |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
You can also use several other ways to do it, instead of using .format in the end. For example: name = "Martin" age = 25 formatted_string = "My name is {} and I am {} years old.".format(name, age) Another way: name = "Martin" age = 25 formatted_string = f"My name is {name} and I am {} years old." |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Select Topic Area
General
Body
String formatting using the format() method in Python is a flexible way to insert variables into strings. Here's how it works:
Basic Syntax:
python
Copy code
"Your text here {}".format(value)
The curly braces {} act as placeholders that will be replaced by the values passed to the format() method.
Example 1: Simple Formatting
python
Copy code
name = "Martin"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
Output:
csharp
Copy code
My name is Martin and I am 25 years old.
Example 2: Using Positional and Keyword Arguments
Positional Arguments: You can specify the order by placing numbers inside the curly braces.
Keyword Arguments: You can assign names to placeholders and pass values by keywords.
python
Copy code
Positional Arguments
formatted_string = "My name is {0} and I am {1} years old.".format("Martin", 25)
print(formatted_string)
Keyword Arguments
formatted_string = "My name is {name} and I am {age} years old.".format(name="Martin", age=25)
print(formatted_string)
Output for both:
csharp
Copy code
My name is Martin and I am 25 years old.
Example 3: Formatting Numbers
You can also format numbers (e.g., specify decimal places, align text, etc.).
python
Copy code
pi = 3.14159
formatted_pi = "The value of pi is {:.2f}".format(pi) # Rounds pi to 2 decimal places
print(formatted_pi)
Output:
csharp
Copy code
The value of pi is 3.14
Example 4: Padding and Aligning Text
You can pad text with spaces or other characters and align it (left, right, or center).
python
Copy code
formatted_string = "{:<10} | {:^10} | {:>10}".format("left", "center", "right")
print(formatted_string)
Output:
scss
Copy code
left | center | right
In this case:
< means left-align,
^ means center-align,
Beta Was this translation helpful? Give feedback.
All reactions