30 字符串的基本操作 格式化字符串(%,Template類,format方法*****)

Python視頻課程(5)—Python字符串
第一課  字符串的基本操作
 # 字符串:基本操作        字符串取單個字母 
s1 = "I love python."
print(s1[7])            # p
print(s1[11])           # o
#  print(s1[15])        # 超過字符串長度 會報錯

#  利用分片截取字符串的子字符串    取一段區間的字符串  
print(s1[7:13])         # python
print(s1[7:])           # python.

print(s1[::2])          # Ilv yhn    取奇數位置的字母 

s2 = "a b c d e f g"
print(s2[::2])          # abcdefg     取奇數位置的字母  

s3 = "abc"
print(s3 * 10)          # abcabcabcabcabcabcabcabcabcabc

print("python" in s1)   # True
print("java" in s1)     # False
print("java" not in s1) # True

# 求程度  求最大值 最小值 
print(len(s1))          # 14
print(max(s1))          # y
print(min(s1))          # 一個空格     字符串的大小上已acall嗎值來判斷的

小結:
講了字符串的取單個單詞  字符串的索引取單詞(取一段區間的字符串) 分片截取子字符串(需要指定開始索引和結束索引) 過濾不需要的值  用*來使得字符串想成複製字符串 用函數in 或者not in來判斷單詞是否在字符串中 
下面講解python中的字符串 有哪些高級的用法  很重要 
第二課 格式化字符串基礎  # 字符串格式化就是把一個或多個值替換另一個字符串的某個標記 通俗一點講 就是替換字符串的標記 
# 字符串格式化基礎

# 什麼叫字符串格式化:靜態和動態兩部分  
# Hello Bill    Hello 李寧   Hello 張三
# Hello param_name  模板
# 字符串格式化就是把一個或多個值替換另一個字符串的某個標記
# 也就是把 靜態不變的變成一個模板,把動態部分就像一個函數一下,在要用的時候,把值再放進去 // 在特定的場景下 最後形成一個完成的問候語句 

小結:
# %:格式化字符串   %s:字符串  %f 浮點數   %d 整數   (把格式化的值原樣輸出,也可以改變輸出的值,比如下面的例子求pi的值保留2位)

# step1:定義一個模板  %s:字符串 模板中會有靜態部分 和 動態部分 
formatStr = "Hello %s,Today is %s,Are there any activities today?"
# step2:準備要替換標記的值 這2個值我們可以用元組來指定 
values = ("John", "Wednesday")
# step3:替換標記
print(formatStr % values) # Hello John,Today is Wednesday,Are there any activities today?

# %f 浮點數   %d 整數
from math import pi
formatStr = "PI是圓周率,PI的值是%.2f(保留小數點後%d位)"
values1 = (pi,2)
print(formatStr % values1) # PI是圓周率,PI的值是3.14(保留小數點後2位)

formatStr1 = "這件事的成功率是%d%%,如果有%s參與的話,成功率會提升至%d%%"   # %d%% 後面的2個% 表示 保留 % 
values2 = (56, "John", 70)
print(formatStr1 % values2) # 這件事的成功率是56%,如果有John參與的話,成功率會提升至70%

formatStr2 = "這件事的成功率是%d%%,如果有%s參與的話,成功率會提升至%d%%"
values2 = (56, "John",70,33)
print(formatStr2 % values2) # values2定義的元組值多了或者少了,都會拋出異常
第三課 使用Template類格式化字符串 (把格式化的值原樣輸出)
# 用Template類格式化字符串  無論用什麼方法去格式化字符串 都少不了2個 一個是標記 一個是用什麼方法啓格式化字符串 
# 標記 $name   $age   $price    // 這個和我們的 shell 中的 引用變量有點像
# 用什麼方式來格式化字符串:substitute 方法

from string import Template
template1 = Template("$lang是我最喜歡的編程語言,$lang非常容易學習,而且功能強大.")
print(template1.substitute(lang = 'Python'))    # 這裏 調用 關鍵字參數 lang 
# Python是我最喜歡的編程語言,Python非常容易學習,而且功能強大.

template2 = Template("${s}stitute")
print(template2.substitute(s = "sub"))
# substitute

template3 = Template("$dollar$$相當於多少$pounds")         # $dollar$$  後面的就表是 原始的值 
print(template3.substitute(dollar =20, pounds = "英鎊"))
# 20$相當於多少英鎊

template4 = Template("$dollar$$相當於多少$pounds")
data = {}   # 這是用字典的方式 這個後面詳細都講到      這一部分用的是字典來進行格式化的 
data['dollar'] = 100
data['pounds'] = '英鎊' 

print(template4.substitute(data))
# 100$相當於多少英鎊 

from string import Template
template01 = Template("Hello $name,Today is $date,Are there any activities today?")
print(template01.substitute(name = "majihui",date = "Wednesday"))
#Hello majihui,Today is Wednesday,Are there any activities today?

template02 = Template("PI是圓周率,值爲$pi(保留$num位小數)")
print(template02.substitute(pi = pi ,num = 2))
# PI是圓周率,值爲3.141592653589793(保留2位小數)

template03 = Template("這件事的成功率是$num1,如果有$name參與的話,成功率會提升至$num2")
print(template03.substitute(num1 = '50%' ,name = "majihui", num2 = '60%'))
# 這件事的成功率是50%,如果有majihui參與的話,成功率會提升至60%
第四課  使用format方法格式化字符串 (把格式化的值原樣輸出)
# 使用format方法格式化字符串   也就是說,我們用字符串本身的format方法去格式化字符串本身 

# 標記(格式化參數):{...}
# 如何進行格式化:"template".format(...)

# 按順序來指定格式化參數值
s1 = "Today is {}, the temperature is {} degrees."
print(s1.format("Saturday", 30))
# Today is Saturday, the temperature is 30 degrees.

# 使用命名格式化參數
s2 = "Today is {week}, the temperature is {degree} degrees."
print(s2.format(week = "Sunday", degree= 21))
print(s2.format(degree= 21,week = "Sunday"))
# Today is Sunday, the temperature is 21 degrees.

# 混合使用順序格式化參數和命名格式化參數
s3 = "Today is {week}, {}, the {} templature is {degree} degrees."
print(s3.format("abcd", 1234, degree = 43, week="Sunday"))
# print(s3.format("abcd", degree = 43,1234,  week="Sunday"))  # 拋出異常 前面必須爲順序的傳入參數值 
# Today is Sunday, abcd, the 1234 templature is 43 degrees.

# 使用序號格式化參數   加序號,從0開始 
s4 = "Today is {week}, {1}, the {0} temperature is {degree} degrees."
print(s4.format("abcd",1234,degree=44,week="Sunday"))
# Today is Sunday, 1234, the abcd temperature is 44 degrees.

# 獲取列表中的指定值
fullname = ["Bill", "Gates"]
s5 = "Mr. {name[1]}"
print(s5.format(name = fullname)) # Mr. Gates
#s7 = "Mr. {fullname[0]}"                #  我用都這種方法不對  這個是不對的 
#print(s7.format("Mr. {fullname[0]}")) 

import math
s6 = "The {mod.__name__} module defines the value {mod.pi} for PI"    # .__name__ 就是模塊的一個方法,可以直接用 
print(s6.format(mod = math))
# The math module defines the value 3.141592653589793 for PI 

print("-----------------------")
s1 = "Hello {},Today is {},Are there any activities today?"
print(s1.format("majihui","Wednesday"))
# Hello majihui,Today is Wednesday,Are there any activities today?

s2 = "PI是圓周率,值爲{pi}(保留2位小數)"
print(s2.format(pi = pi))
# PI是圓周率,值爲3.141592653589793(保留2位小數)

s3 = "這件事的成功率是{},如果有{}參與的話,成功率會提升至{}"
print(s3.format('50%','majihui','60%'))
# 這件事的成功率是50%,如果有majihui參與的話,成功率會提升至60%
第五課 更進一步控制字符串格式化參數  字符串格式化類型符  format方法
# 更進一步控制字符串格式化參數

# 字符串格式化類型符 
# repr函數  repr('a') = 'a'  str('a') = a      repr輸出的就是py的字符串的輸出格式 
# 原樣輸出的 用 !s        調用repr函數輸出用 !r       Unicode編碼輸出用 !a
s1 = "原樣輸出:{first!s}  調用repr函數:{first!r}  輸出Unicode編碼:{first!a}"
print(s1.format(first = "中"))
# 輸出的結果爲  : 原樣輸出:中  調用repr函數:'中'  輸出Unicode編碼:'\u4e2d'

# 將一個整數按浮點數格式輸出         :f 字符串格式化類型符  
s2 = "整數:{num}  浮點數:{num:f}"
print(s2.format(num=123))
# 整數:123  浮點數:123.000000

# 進制轉換
s3 = "十進制:{num}  二進制:{num:b}  八進制:{num:o}   十六進制:{num:x}"
print(s3.format(num = 78))
# 十進制:78  二進制:1001110 八進制:116  十六進制:4e 

# 原有的方式是這樣的 
n = 78
print(bin(n))   # 0b1001110
print(oct(n))   # 0o116
print(hex(n))   # 0x4e

# 將整數按科學計數法
s4 = "科學計數法:{num:e}"
print(s4.format(num =6789))
# 科學計數法:6.789000e+03
m = 6789
print(format(m,'e'))
# 6.789000e+03

#  將浮點數按百分比輸出
s5 = "百分比:{num:%}"
print(s5.format(num = 0.34))
# 百分比:34.000000%

小結 
'''
a  將字符串按Unicode編碼輸出
b  將一個整數格式化爲一個二進制數
c  將一個整數解釋成ASCII
d  將整數格式化爲十進制的數
e/E  科學計數法表示
f/F  將一個整數格式化爲浮點數,(nan和inf)轉換爲小寫
g/G  會根據整數值的位數,在浮點數和科學計數法之間切換,在整數位超過6位時,與e相同,否則與f相同
o   將一個整數格式化爲八進制
s   按原樣格式化字符串
x/X 將一個整數格式化爲十六進制數
%   將一個數值格式化爲百分比形式

'''

小結:
推薦使用format 去格式化字符串,也可以格式化數字,其實都是可以的,看個人的選擇。
參考鏈接: 07 python 數字的格式化輸出 format(重要) https://blog.51cto.com/12445535/2463368

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章