- Get link
- Other Apps
- Get link
- Other Apps
String formatting
by format() Method:
- Sometimes selected part of a string is not in control then we use the format() method to control it.- In string, add placeholders (in curly brackets {}) to run values through the format() method.
Single value:
- For a single value add one placeholder in the string.Below code explanation:
- We take two variables. (money and str)
- We call the format() method with the str variable and to get the value of money place the money variable in the format() method in the print() function.
- Syntax: variable1 = Any Value
variable2 = "I have {} rupees"
print(variable2.format(variable1))
Multiple values:
- For multiple values add more placeholders in the string.Below code explanation:
- We take four variables. (name, course, year, and str)
- We call the format() method with the str variable and to get the value of all variables place all variables in the format() method (septate with a comma) in the print() function.
- Syntax: variable1 = Any Value
variable2 = Any Value
variable3 = Any Value
variable4 = "hi {}, hi{}, hi {}"
print(variable2.format(variable1, variable2, variable3))
Index numbers:
- In index numbers (a number in curly brackets {}) are placed the values in the right placeholders.Below code explanation:
- We take four variables. (name, course, year, and str)
- We call the format() method with the str variable and to get the value of all variables place all variables in the format() method (septate with a comma) in the print() function.
- Syntax: variable1 = Any Value
variable2 = Any Value
variable3 = Any Value
variable4 = "hi {}, hi{}, hi {}"
print(variable2.format(variable1, variable2, variable3))
Named indexes:
- In named indexes enter the objects name (in curly brackets {}) to get their values.Below code explanation:
- We take two objects. (name, age)
- We call the format() method with the self variable and create two object in format() method (septate with a comma) in the print() function.
- Add object's name (in curly brackets {}) in the string of self variable to get their values.
- Syntax: self = "my name is {object1}, i'm {object2} years old"
print(self.format(object1 = Any Value, object2 = Any Value))
Return a Number with Two Decimals:
- If we have user data with more than 2 decimals but we don’t need all decimals then we need to use this format.
Below code explanation:
- We take two variables. (name and str)
- We call the format() method with the str variable and to get the value of dollar variables place dollar variables in the format() method in the print() function.
- Format: {:.2f} for two decimal.
- Above format used (in curly bracket {}) in the string of str variable.
- Syntax: variable1 = Any Value
variable2 = "{:.2f} dollars"
print(variable2.format(variable1))
- Get link
- Other Apps
Comments
Post a Comment