Skip to content
Fix Code Error

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

March 13, 2021 by Code Error
Posted By: Anonymous

Python 2.6 introduced the str.format() method with a slightly different syntax from the existing % operator. Which is better and for what situations?

Python 3.6 has now introduced another string formatting format of string literals (aka "f" strings) via the syntax f"my string". Is this formatting option better than the others?

  1. The following uses each method and has the same outcome, so what is the difference?

     #!/usr/bin/python
     sub1 = "python string!"
     sub2 = "an arg"
    
     sub_a = "i am a %s" % sub1
     sub_b = "i am a {0}".format(sub1)
     sub_c = f"i am a {sub1}"
    
     arg_a = "with %(kwarg)s!" % {'kwarg':sub2}
     arg_b = "with {kwarg}!".format(kwarg=sub2)
     arg_c = f"with {sub2}!"
    
     print(sub_a)    # "i am a python string!"
     print(sub_b)    # "i am a python string!"
     print(sub_c)    # "i am a python string!"
    
     print(arg_a)    # "with an arg!"
     print(arg_b)    # "with an arg!"
     print(arg_c)    # "with an arg!"
    
  2. Furthermore when does string formatting occur in Python? For example, if my logging level is set to HIGH will I still take a hit for performing the following % operation? And if so, is there a way to avoid this?

     log.debug("some debug info: %s" % some_info)
    

Solution

To answer your first question… .format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You’d think the following would always work:

"hi there %s" % name

yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you’d need to do

"hi there %s" % (name,)   # supply the single argument as a single-item tuple

which is just ugly. .format doesn’t have those issues. Also in the second example you gave, the .format example is much cleaner looking.

Why would you not use it?

  • not knowing about it (me before reading this)
  • having to be compatible with Python 2.5

To answer your second question, string formatting happens at the same time as any other operation – when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so in your log.debug example, the expression "some debug info: %s"%some_infowill first evaluate to, e.g. "some debug info: roflcopters are active", then that string will be passed to log.debug().

Answered By: Anonymous

Related Articles

  • Form field border-radius is not working only on the…
  • How to properly do JSON API GET requests and assign…
  • Trouble with boxes appearing/hiding based on selection
  • How to parse JSON with XE2 dbxJSON
  • Azure Availability Zone ARM Config
  • The 'compilation' argument must be an instance of…
  • Generating a drop down list of timezones with PHP
  • Search match multiple values in single field in…
  • What does this symbol mean in JavaScript?
  • Event Snippet for Google only shows one event while…
  • no match for ‘operator
  • Avoid creating new session on each axios request laravel
  • mongodb group values by multiple fields
  • loop and eliminate unwanted lines with beautiful soup
  • What are the undocumented features and limitations…
  • Why does this Azure Resource Manager Template fail…
  • NullpointerException error while working with…
  • Octave using 'for' statement to show two animations…
  • ORA-01008: not all variables bound. They are bound
  • Most effective way to parse JSON Objects
  • Azure CLI - az deployment group create -…
  • How do I limit the number of digits from 6 to 4 in…
  • Does moment.js allow me to derive a timezone…
  • Adding Google Translate to a web site
  • problem with client server unix domain stream…
  • How to traverse the complex nested Json in C# and…
  • Postgres could not connect to server
  • Angular 12 - Generating browser application bundles…
  • Python JSON TypeError : list indices must be…
  • Siemens LOGO! PLC data in the wrong order
  • Can't upload files with Apollo-client GraphQL in…
  • C# Get YouTube videoId from Json
  • Python scrape JS data
  • coercing to Unicode: need string or buffer, NoneType…
  • ./components/Avatar.tsx Error: Cannot find module…
  • Docker compose fails to start a service with an…
  • How to build correlation matrix plot using specified…
  • error NG6002: Appears in the NgModule.imports of…
  • How do I remove single children in a tree?
  • Why does `which` print out a script?
  • One to many relationship in two JSON arrays, lookup…
  • Need constraints for y position or height when…
  • Reference — What does this symbol mean in PHP?
  • Error Stack Overflow when trying to hide buttons in…
  • TypeError: players.map is not a function
  • Python is not calling fucntions properly
  • How do you list volumes in docker containers?
  • Posting array of objects to REST API with ReactJS
  • Python - Read JSON - TypeError: string indices must…
  • Scraping text after a span in with Regex (and Requests)
  • php display array results by first letter from select option
  • Function runs into an error after successfully…
  • state data can not be set using useState in reactjs
  • hide select options using only css
  • How to query Json field so the keys are the column…
  • Split JSON python string to pass to function
  • Validate that a string is a positive integer
  • Blazor Can't Update UI
  • How to use Servlets and Ajax?
  • python pandas - add unique Ids in column from master…
  • How to blur the background after click on the button…
  • Accessing bash command line args [email protected] vs $*
  • Combining pyOSC with pyQT5 / Threading?
  • Executing java command on ENTRYPOINT of Dockerfile…
  • How can i use `parse = T` and functions like round…
  • correct way to use super (argument passing)
  • passing json to other vue component
  • configure: error: C compiler cannot create executables
  • Fragment Not Showing in the Activity
  • Vega-lite data transformation to un-nest objects
  • R - Apply function to list of lm summaries
  • Add to PATH from Laravel Sail Dockerfile
  • How do we split words from a html file using string…
  • Remove Text from the edit text when edit text is focused
  • Smart way to truncate long strings
  • How to determine the current iPhone/device model?
  • List comprehension and converting an argument to…
  • Htaccess 301 redirect from en urls to main urls
  • MaterialCardView is in front of NavigationView. How…
  • Need to split output into an javascript array
  • How to reverse $unwind or re-assemble after $lookup?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Conditional render label Color base on another field value
  • How can I successfully Build gRPC in C++?
  • I'm working on pagination for my project. How do I…
  • How to show multiple select options when user select…
  • Adding a unique id to appended forms in Jquery or Javascript
  • Js Calculation based on radio button, and some problems
  • C# parse FHIR bundle - read resources
  • C++ template,typename and operator
  • How do I get currency exchange rates via an API such…
  • Javascript filtering a nested array to exclude…
  • JSON Schema - How to apply conditionals based on…
  • Can't understand the difference between declaring a…
  • Errorbars and bar plots having different positions in ggplot
  • Svelte application not working on android version…
  • Python Inserting headers for CSV file when…
  • How can I center all my contents in html?
  • How to check if a string contains text from an array…
  • What to change in circular barplot in R?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Is there a way to cache GitHub credentials for pushing commits?

Next Post:

Convert character to ASCII code in JavaScript

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error