Summary of character string format in Python3 Whether to live with the old model or the new model

Click here for the blog article: Summary of string format methods in python3

I couldn't remember it easily and it was hard so I decided to write it down and put it together. I pray that the retention in my memory will be even a little decent. ..

Old way (although still in use)


'This is our %s' % 'string'
  # This is our string

print('we are learning %s %s' % ('Python', '3'))
  # we are learning Python 3

print('we are learning %(lang)s %(ver)s' % {'lang': 'Python', 'ver': '3'})
  #we are learning Python 3

New model (recommended method)

Attach the format method after the string. The place to insert is basically specified by ** {} **.

'This is our string {}'.format('in Python')

'{} {} {}'.format('a','b','c') 
  # 'a b c'

'{2} {1} {0}'.format('a','b','c') 
  #c b a
  #You can specify like an index

'we are learning {lang} {ver}'.format(lang = 'Python', version = '3') 
  #we are learning Python 3

language = ('Python', '3')
'we are learning {0[0]} {0[1]}'.format(language)
  #we are learning Python 3

Advanced edition

I use the format method, but it seems that I can do more than I expected.

--Convert numbers to binary --Create character strings with left justification, right justification, center justification, etc.

animal = ('Dog', 'Cat')
name = ('Maggie', 'Missy')

'I have a {0[0]} named {1[0]}'.format(animal,name)
	#I have a dog named Maggie

'I have a {0[1]} named {1[1]}'.format(animal,name)
	#I have a cat named Missy

'{:<50}'.format('aligned left')
  #'aligned left          
  #Prepare 50 indexes and enter characters left-justified
                            '{:a<50}.format('aligned left ')
  #'aligned left aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
  #The top is hard to see, so I filled it with a

'{:>50}'.format('aligned right')

'{:^50}'.format('aligned center')

'{:$^50}'.format('More Money')
  #'$$$$$$$$$$$$$$$$$$$$More Money$$$$$$$$$$$$$$$$$$$$'

'Binary: {0:b}'.format(324)
	#Binary: 101000100

'{:,}'.format(123456787654321)
	#'123,456,787,654,321'

  #It seems that the result of division can also be displayed
correct = 78
total = 84
'Your score is: {:.1%}'.format(correct/total)
	#'Your score is: 92.9%'
'Your score is: {:.3%}'.format(correct/total)
	#'Your score is 92.857%'

Magnificent note-taking. For the time being, I want to be able to put it in my head and use it.

Recommended Posts

Summary of character string format in Python3 Whether to live with the old model or the new model
[Introduction to Python] How to write a character string with the format function
[Introduction to Python] Thorough explanation of the character string type used in Python!
[VBA] Function to judge whether the character string of UTF-8 file system is 255 or less and function to count UTF-8 character string in bytes
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
How to quickly count the frequency of appearance of characters from a character string in Python?
[Introduction to Python] How to split a character string with the split function
Output the contents of ~ .xlsx in the folder to HTML with Python
I want to extract an arbitrary URL from the character string of the html source with python
I want to batch convert the result of "string" .split () in Python
I tried to streamline the standard role of new employees with Python
How to format a list of dictionaries (or instances) well in Python
I tried to predict the behavior of the new coronavirus with the SEIR model.
How to input a character string in Python and output it as it is or in the opposite direction.
Summary of how to import files in Python 3
Summary of how to use MNIST in Python
Convert the character code of the file with Python3
Divides the character string by the specified number of characters. In Ruby and Python.
What you want to memorize with the basic "string manipulation" grammar of python
How to get a list of files in the same directory with python
I tried to automatically send the literature of the new coronavirus to LINE with Python
[Python] Summary of eval / exec functions + How to write character strings with line breaks
System trade starting with Python3: Bio-health stocks to look at in the new Corona
How to convert / restore a string with [] in python
Summary of tools needed to analyze data in Python
How to get the number of digits in Python
How to identify the element with the smallest number of characters in a Python list?
Store Japanese (multibyte character string) in sqlite3 of python
[Python] How to expand variables in a character string
Convert the image in .zip to PDF with Python
Get the result in dict format with Python psycopg2
[Python] Leave only the elements that start with a specific character string in the array
[Introduction to Python] Summary of functions and methods that frequently appear in Python [Problem format]
Summary of the basic flow of machine learning with Python
[Python] Summary of how to specify the color of the figure
How to use the model learned in Lobe in Python
How to count the number of occurrences of each element in the list in Python with weight
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
I tried to summarize the string operations of Python
Use hash to lighten collision detection of about 1000 balls in Python (related to the new coronavirus)
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
[Python3] Format the character string using the variable name as the key.
I tried to find the entropy of the image with python
Try scraping the data of COVID-19 in Tokyo with Python
Find out the apparent width of a string in python
Calculate the square root of 2 in millions of digits with python
[For beginners] Summary of standard input in Python (with explanation)
[Homology] Count the number of holes in data with Python
Try to automate the operation of network devices with Python
Get the source of the page to load infinitely with python.
What's new in Python 3.10 (Summary)
[Python 2/3] Parse the format string
What's new in Python 3.9 (Summary)
String format with Python% operator
Put the process to sleep for a certain period of time (seconds) or more in Python
I tried to predict the number of domestically infected people of the new corona with a mathematical model
Memo of the program to get the date in two digits with javascript, Ruby, Python, shell script
Try to calculate the position of the transmitter from the radio wave propagation model with python [Wi-Fi, Beacon]
Specify the encoding of the unicode string in the Python 2.x print statement
Determine the date and time format in Python and convert to Unixtime