Movatterモバイル変換


[0]ホーム

URL:


Menu
×
Sign In
+1 Get Certified For Teachers Spaces Plus Get Certified For Teachers Spaces Plus
   ❮     
     ❯   

Python Tutorial

Python HOMEPython IntroPython Get StartedPython SyntaxPython CommentsPython VariablesPython Data TypesPython NumbersPython CastingPython StringsPython BooleansPython OperatorsPython ListsPython TuplesPython SetsPython DictionariesPython If...ElsePython MatchPython While LoopsPython For LoopsPython FunctionsPython LambdaPython ArraysPython OOPPython Classes/ObjectsPython InheritancePython IteratorsPython PolymorphismPython ScopePython ModulesPython DatesPython MathPython JSONPython RegExPython PIPPython Try...ExceptPython String FormattingPython User InputPython VirtualEnv

File Handling

Python File HandlingPython Read FilesPython Write/Create FilesPython Delete Files

Python Modules

NumPy TutorialPandas TutorialSciPy TutorialDjango Tutorial

Python Matplotlib

Matplotlib IntroMatplotlib Get StartedMatplotlib PyplotMatplotlib PlottingMatplotlib MarkersMatplotlib LineMatplotlib LabelsMatplotlib GridMatplotlib SubplotMatplotlib ScatterMatplotlib BarsMatplotlib HistogramsMatplotlib Pie Charts

Machine Learning

Getting StartedMean Median ModeStandard DeviationPercentileData DistributionNormal Data DistributionScatter PlotLinear RegressionPolynomial RegressionMultiple RegressionScaleTrain/TestDecision TreeConfusion MatrixHierarchical ClusteringLogistic RegressionGrid SearchCategorical DataK-meansBootstrap AggregationCross ValidationAUC - ROC CurveK-nearest neighbors

Python DSA

Python DSALists and ArraysStacksQueuesLinked ListsHash TablesTreesBinary TreesBinary Search TreesAVL TreesGraphsLinear SearchBinary SearchBubble SortSelection SortInsertion SortQuick SortCounting SortRadix SortMerge Sort

Python MySQL

MySQL Get StartedMySQL Create DatabaseMySQL Create TableMySQL InsertMySQL SelectMySQL WhereMySQL Order ByMySQL DeleteMySQL Drop TableMySQL UpdateMySQL LimitMySQL Join

Python MongoDB

MongoDB Get StartedMongoDB Create DBMongoDB CollectionMongoDB InsertMongoDB FindMongoDB QueryMongoDB SortMongoDB DeleteMongoDB Drop CollectionMongoDB UpdateMongoDB Limit

Python Reference

Python OverviewPython Built-in FunctionsPython String MethodsPython List MethodsPython Dictionary MethodsPython Tuple MethodsPython Set MethodsPython File MethodsPython KeywordsPython ExceptionsPython Glossary

Module Reference

Random ModuleRequests ModuleStatistics ModuleMath ModulecMath Module

Python How To

Remove List DuplicatesReverse a StringAdd Two Numbers

Python Examples

Python ExamplesPython CompilerPython ExercisesPython QuizPython ServerPython SyllabusPython Study PlanPython Interview Q&APython BootcampPython CertificatePython Training

PythonString Formatting


F-String was introduced in Python 3.6,and is now the preferred way of formatting strings.

Before Python 3.6 we had to use theformat() method.


F-Strings

F-string allows you to format selected parts of a string.

To specify a string as an f-string, simply put anf in front of the string literal, like this:

Example

Create an f-string:

txt = f"The price is 49 dollars"
print(txt)
Try it Yourself »

Placeholders and Modifiers

To format values in an f-string, add placeholders{}, a placeholder can contain variables,operations, functions, and modifiers to format the value.

Example

Add a placeholder for theprice variable:

price = 59
txt = f"The price is {price} dollars"
print(txt)
Try it Yourself »

A placeholder can also include amodifierto format the value.

A modifier is included by adding a colon: followed by a legal formatting type, like.2f which means fixed point number with 2 decimals:

Example

Display the price with 2 decimals:

price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Try it Yourself »

You can also format a value directly without keeping it in a variable:

Example

Display the value95 with 2 decimals:

txt = f"The price is {95:.2f} dollars"
print(txt)
Try it Yourself »


Perform Operations in F-Strings

You can perform Python operations inside the placeholders.

You can do math operations:

Example

Perform a math operation in the placeholder, and return the result:

txt = f"The price is {20 * 59} dollars"
print(txt)
Try it Yourself »

You can perform math operations on variables:

Example

Add taxes before displaying the price:

price = 59
tax = 0.25
txt = f"The price is {price + (price * tax)} dollars"
print(txt)
Try it Yourself »

You can performif...else statements inside the placeholders:

Example

Return "Expensive" if the price is over 50, otherwise return "Cheap":

price = 49
txt = f"It is very {'Expensive' if price>50 else 'Cheap'}"

print(txt)
Try it Yourself »

Execute Functions in F-Strings

You can execute functions inside the placeholder:

Example

Use the string methodupper()to convert a value into upper case letters:

fruit = "apples"
txt = f"I love {fruit.upper()}"
print(txt)
Try it Yourself »

The function does not have to be a built-in Python method, you can create your own functions and use them:

Example

Create a function that converts feet into meters:

def myconverter(x):
  return x * 0.3048

txt = f"The plane is flying at a {myconverter(30000)} meter altitude"
print(txt)
Try it Yourself »

More Modifiers

At the beginning of this chapter we explained how to use the.2f modifier to format a number into a fixed point number with 2 decimals.

There are several other modifiers that can be used to format values:

Example

Use a comma as a thousand separator:

price = 59000
txt = f"The price is {price:,} dollars"
print(txt)
Try it Yourself »

Here is a list of all the formatting types.

Formatting Types
:<Try itLeft aligns the result (within the available space)
:>Try itRight aligns the result (within the available space)
:^Try itCenter aligns the result (within the available space)
:=Try itPlaces the sign to the left most position
:+Try itUse a plus sign to indicate if the result is positive or negative
:-Try itUse a minus sign for negative values only
Try itUse a space to insert an extra space before positive numbers (and a minus sign before negative numbers)
:,Try itUse a comma as a thousand separator
:_Try itUse a underscore as a thousand separator
:bTry itBinary format
:cConverts the value into the corresponding Unicode character
:dTry itDecimal format
:eTry itScientific format, with a lower case e
:ETry itScientific format, with an upper case E
:fTry itFix point number format
:FTry itFix point number format, in uppercase format (showinf andnan asINF andNAN)
:gGeneral format
:GGeneral format (using a upper case E for scientific notations)
:oTry itOctal format
:xTry itHex format, lower case
:XTry itHex format, upper case
:nNumber format
:%Try itPercentage format

String format()

Before Python 3.6 we used theformat() method to format strings.

Theformat() method can still be used,but f-strings are faster and the preferred way to format strings.

The next examples in this page demonstrates how to format strings with theformat() method.

Theformat() method also uses curly brackets as placeholders{}, but the syntax is slightly different:

Example

Add a placeholder where you want to display the price:

price = 49
txt = "The price is {} dollars"
print(txt.format(price))
Try it Yourself »

You can add parameters inside the curly brackets to specify how to convert the value:

Example

Format the price to be displayed as a number with two decimals:

txt = "The price is {:.2f} dollars"
Try it Yourself »

Check out all formatting types in ourString format() Reference.


Multiple Values

If you want to use more values, just add more values to the format() method:

print(txt.format(price, itemno, count))

And add more placeholders:

Example

quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Try it Yourself »

Index Numbers

You can use index numbers (a number inside the curly brackets{0}) to be sure the values are placed in the correct placeholders:

Example

quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Try it Yourself »

Also, if you want to refer to the same value more than once, use the index number:

Example

age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
Try it Yourself »

Named Indexes

You can also use named indexes by entering a name inside the curly brackets{carname}, but then you must use names when you pass the parameter valuestxt.format(carname = "Ford"):

Example

myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
Try it Yourself »


 
Track your progress - it's free!
 

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp