Movatterモバイル変換


[0]ホーム

URL:


Sorry, we no longer support your browser
Please upgrade toMicrosoft Edge,Google Chrome, orFirefox. Learn more about ourbrowser support.
Skip to main content
Stack Overflow
  1. About
  2. For Teams
Loading…
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

You are notlogged in. Your edit will be placed in a queue until it ispeer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

String formatting: % vs. .format vs. f-string literal

There are various string formatting methods:

  • Python <2.6:"Hello %s" % name
  • Python 2.6+:"Hello {}".format(name)   (usesstr.format)
  • Python 3.6+:f"{name}"   (uses f-strings)

Which is better, and for what situations?


  1. The following methods have the same outcome, so what is the difference?

    name = "Alice""Hello %s" % name"Hello {0}".format(name)f"Hello {name}"# Using named arguments:"Hello %(kwarg)s" % {'kwarg': name}"Hello {kwarg}".format(kwarg=name)f"Hello {name}"
  2. When does string formatting run, and how do I avoid a runtime performance penalty?


If you are trying to close a duplicate question that is just looking for a way to format a string, please useHow do I put a variable’s value inside a string?.

Answer*

Draft saved
Draft discarded
Cancel
5
  • 5
    This looks more unreadable than necessary compared to the equivalent'x is {0}, y is {1}'.format(a.x, a.y). Should only be used when thea.x operation is very costly.CommentedMar 29, 2015 at 14:03
  • 13
    @dtheodor With a tweak to use a keyword argument instead of positional argument...'x is {a.x}, y is {a.y}'.format(a=a). More readable than both examples.CommentedApr 17, 2015 at 21:11
  • 1
    @CivFan Or, if you have more than one object,'x is {a.x}, y is {a.y}'.format(**vars())CommentedJun 18, 2015 at 17:02
  • 1
    Also note this one in the same fashion:'{foo[bar]}'.format(foo={'bar': 'baz'}).CommentedJul 23, 2016 at 22:01
  • 5
    This is incredibly useful for customer-facing applications, where your application supplies a standard set of formatting options with a user-supplied format string. I use this all the time. The configuration file, for instance, will have some "messagestring" property, which the user can supply withYour order, number {order[number]} was processed at {now:%Y-%m-%d %H:%M:%S}, will be ready at about {order[eta]:%H:%M:%S} or whatever they wish. This is far cleaner than trying to offer the same functionality with the old formatter. It makes user-supplied format strings way more powerful.CommentedSep 30, 2016 at 21:33
Add a comment | 
How to Edit
  • Correct minor typos or mistakes
  • Clarify meaning without changing it
  • Add related resources or links
  • Always respect the author’s intent
  • Don’t use edits to reply to the author
How to Format
  • create code fences with backticks ` or tildes ~
    ```
    like so
    ```
  • add language identifier to highlight code
    ```python
    def function(foo):
        print(foo)
    ```
  • put returns between paragraphs
  • for linebreak add 2 spaces at end
  • _italic_ or**bold**
  • indent code by 4 spaces
  • backtick escapes`like _so_`
  • quote by placing > at start of line
  • to make links (use https whenever possible)
    <https://example.com>
    [example](https://example.com)
    <a href="https://example.com">example</a>
How to Tag

A tag is a keyword or label that categorizes your question with other, similar questions. Choose one or more (up to 5) tags that will help answerers to find and interpret your question.

  • complete the sentence:my question is about...
  • use tags that describe things or concepts that areessential, not incidental to your question
  • favor usingexisting popular tags
  • read the descriptions that appear below the tag

If your question is primarily about a topic for which you can't find a tag:

popular tags »


lang-py

[8]ページ先頭

©2009-2025 Movatter.jp