1. 程式人生 > >Python String Formatting

Python String Formatting

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

format() method allows you format string in any way you want.

Syntax: template.format(p1,p1,...

.,k1=v1,k2=v2)

template is a string containing format codes, format()  method uses it’s argument to substitute value for each format codes. For e.g

1>>>'Sam has {0} red balls and {1} yellow balls'.format(12,31)

{0}  and {1}

  are format codes. The format code {0}  is replaced by the first argument of format()  i.e 12 , while {1}  is replaced by the second argument of format()  i.e 31 .

Expected Output:

1Sam has12red balls and31yellow balls

This technique is okay for simple formatting but what if you want to specify precision in floating point number ? For such thing you need to learn more about format codes. Here is the full syntax of format codes.

Syntax: {[argument_index_or_keyword]:[width][.precision][type]}

type  can be used with format codes

Format codes Description
d for integers
f for floating point numbers
b for binary numbers
o for octal numbers
x for octal hexadecimal numbers
s for string
e for floating point in exponent format

Following examples will make things more clear.

Example 1:

1>>>"Floating point {0:.2f}".format(345.7916732)

Here we specify 2  digits of precision and f  is used to represent floating point number.

Expected Output:

1Floating point345.79

Example 2:

12>>>importmath>>>"Floating point {0:10.3f}".format(math.pi)

Here we specify 3  digits of precision, 10  for width and f  for floating point number.

Expected Output:

1Floating point3.142

Example 3:

1"Floating point pi = {0:.3f}, with {1:d} digit precision".format(math.pi,3)

here d  in {1:d} represents integer value.

Expected Output:

1Floating point pi=3.142,with3digit precision

You need to specify precision only in case of floating point numbers if you specify precision for integer ValueError  will be raised.

Example 5:

1'Sam has {1:d} red balls and {0:d} yellow balls'.format(12,31)

Expected Output:

1Sam has31red balls and12yellow balls

Example 6:

1"In binary 4 is {0:b}".format(4)# b for binary, refer to Fig 1.1

Expected Output:

1Inbinary4is100

Example 7:

12array=[34,66,12]"A = {0}, B = {1}, C = {2}".format(*array)

Expected Output:

1'A = 34, B = 66, C = 12'

Example 8:

1234d={'hats':122,'mats':42}

Expected Output:

1"Sam had {hats} hats and {mats} mats".format(**d)

format()  method also supports keywords arguments.

1'Sam has {red} red balls and {green} yellow balls'.format(red=12,green=31)

Note while using keyword arguments we need to use arguments inside {}  not numeric index.

You can also mix position arguments with keywords arguments

12'Sam has {red} red balls, {green} yellow balls \and {0} bats'.format(3,red=12,green=31)

format()  method of formatting string is quite new and was introduced in python 2.6 . There is another old technique  you will see in legacy codes which allows you to format string using %  operator instead of format()  method.

Let’s take an example.

1"%d pens cost = %.2f"%(12,150.87612)

Here we are using template string on the left of % . Instead of {} for format codes we are using % . On the right side of % we use tuple to contain our values. %d and %.2f are called as format specifiers, they begin with % followed by character that represents the data type. For e.g %d  format specifier is a placeholder for a integer, similarly %.2f  is a placeholder for floating point number.

So %d  is replaced by the first value of the tuple i.e 12  and %.2f  is replaced by second value i.e 150.87612 .

Expected Output:

112pens cost=150.88

Some more examples

Example 1:

New: "{0:d} {1:d} ".format(12,31)

Old: "%d %d"%(12,31)

Expected Output:

11231

Example 2:

New: "{0:.2f} {1:.3f}".format(12.3152,89.65431)

Old "%.2f %.3f"%(12.3152,89.65431)

Expected Output:

112.3289.654

Example 3:

New: "{0:s} {1:o} {2:.2f} {3:d}".format("Hello",71,45836.12589,45)

Old:  "%s %o %.2f %d"%("Hello",71,45836.12589,45)

Expected Output:

1Hello10745836.1345

Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive

相關推薦

[Python] String Formatting

side serve col temp mes eth this add access One particularly useful string method is format. The format method is used to construct strin

Python String Formatting Best Practices – Real Python

Remember the Zen of Python and how there should be “one obvious way to do something in Python”? You might scratch your head when you find out that there

Python String Formatting

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and

Python-TypeError: not all arguments converted during string formatting

tro -type error: where mat obj AS print %s Where?   運行Python程序,報錯出現在這一行 return "Unknow Object of %s" % value Why?    %s 表示把 value變量裝換為字

Python 3's f-Strings: An Improved String Formatting Syntax (Guide)

source: https://realpython.com/python-f-strings/ As of Python 3.6, f-strings are a great new way to format strings. Not only are they more read

Python 3's f-Strings: An Improved String Formatting Syntax (Guide)

As of Python 3.6, f-strings are a great new way to format strings. Not only are they more readable, more concise, and less prone to error than other way

Python學習筆記:TypeError: not all arguments converted during string formatting 解決

前言 在學習python中難免犯下一些幼稚的錯誤,為了方便後來人的學習,寫下此篇文件。 問題 TypeError: not all arguments converted during string formatting 舉例 例如:

not all arguments converted during string formatting Python+mysql 寫入資料庫的的錯誤

>>> cur.execute("INSERT INTO foo VALUES (%s)", "bar")    # WRONG >>> cur.execute("INSERT INTO foo VALUES (%s)", ("bar"))

Python string常用函數

一次 pan bcd 索引 col def 第一次 art -1 2017-07-03 23:26:08 1、.replace(self, old, new, count=-1) replace()函數將舊字符串替換為新字符串,最後一個參數count為可選項,表示替換最多c

python string method

str upper enter wap abs final ace style 學習 嗯,學習其它語言沒這樣全練過,嘻嘻 //test.py 1 # -*- coding: UTF-8 -*- 2 3 str = "i am worker" 4 print str.

Python String Methods

capi pan span sta string 第一個 cnblogs div 居中 str.capitalize() # 將字符串的第一個字母變成大寫,其他字母變小寫。對於 8 位字節編碼需要根據本地環境 >>> ‘hello‘.capitaliz

Python String Methods 2

否則 字符連接 ring 新的 包含 world spa bsp 技術 1. Python isalnum()方法 #檢測字符串是否由字母和數字組成 如果 string 至少有一個字符並且所有字符都是字母或數字則返回 True,否則返回 False >>&

TypeError: not all arguments converted during string formatting

tin convert str 就是 ring erro 說明 mat uri print ("So, you‘re 5r old, %r tall and %r heavy." % (age, height, weight)) print ("So, you‘re %r

python string

python string方法 描述string.ljust(width)返回一個原字符串左對齊,並使用空格填充至長度 width 的新字符串\>>> x.ljust(20)‘Hello,wold ‘ string.center(width)返回一個原字符串居中,並使用空格填充

python~string常量及模板

字串常量 >>> import string >>> string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'   >>> string.ascii_lowercas

python string.Template使用

string.Template,將一個string設定為模板,通過替換變數的方法,最終得到想要的string。 1. 用法示例 (改寫 from python官方文件): >>> from string import Template >>>

python string strip 和split

python strip() 函式和 split() 函式的詳解及例項 python strip() 函式和 split() 函式的詳解及例項 一直以來都分不清楚strip和split的功能,實際上strip是刪除的意思;而split則是分割的意思。因此也表示了這兩個功能是完全不一樣的,

Python string 模塊

code upper class spa string port python 打印 註意 In [1]: import string In [2]: string.lowercase # lowercase用於打印所有小寫字母,註意這是string模塊的一

python string join split使用

 python join 和 split方法的使用,join用來連線字串,split恰好相反,拆分字串的。 1.join用法示例  >>>li = ['my','name','is','bob']  >>>' '.join(li) 

Python string 去掉標點符號 最佳實踐

Python 字串去掉標點符號最佳實踐 方法一: str.isalnum: S.isalnum() -> bool Return True if all characters in S are