溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

30 字符串的基本操作 格式化字符串(%,Template類

發(fā)布時間:2020-02-25 10:51:14 來源:網(wǎng)絡(luò) 閱讀:226 作者:馬吉輝 欄目:大數(shù)據(jù)
Python視頻課程(5)—Python字符串
第一課  字符串的基本操作
 # 字符串:基本操作        字符串取單個字母 
s1 = "I love python."
print(s1[7])            # p
print(s1[11])           # o
#  print(s1[15])        # 超過字符串長度 會報錯

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

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

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

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))          # 一個空格     字符串的大小上已a(bǔ)call嗎值來判斷的

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

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

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

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

# %f 浮點數(shù)   %d 整數(shù)
from math import pi
formatStr = "PI是圓周率,PI的值是%.2f(保留小數(shù)點后%d位)"
values1 = (pi,2)
print(formatStr % values1) # PI是圓周率,PI的值是3.14(保留小數(shù)點后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個 一個是標(biāo)記 一個是用什么方法啟格式化字符串 
# 標(biāo)記 $name   $age   $price    // 這個和我們的 shell 中的 引用變量有點像
# 用什么方式來格式化字符串:substitute 方法

from string import Template
template1 = Template("$lang是我最喜歡的編程語言,$lang非常容易學(xué)習(xí),而且功能強(qiáng)大.")
print(template1.substitute(lang = 'Python'))    # 這里 調(diào)用 關(guān)鍵字參數(shù) lang 
# Python是我最喜歡的編程語言,Python非常容易學(xué)習(xí),而且功能強(qiáng)大.

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

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

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

print(template4.substitute(data))
# 100$相當(dāng)于多少英鎊 

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位小數(shù))")
print(template02.substitute(pi = pi ,num = 2))
# PI是圓周率,值為3.141592653589793(保留2位小數(shù))

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

# 標(biāo)記(格式化參數(shù)):{...}
# 如何進(jìn)行格式化:"template".format(...)

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

# 使用命名格式化參數(shù)
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.

# 混合使用順序格式化參數(shù)和命名格式化參數(shù)
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"))  # 拋出異常 前面必須為順序的傳入?yún)?shù)值 
# Today is Sunday, abcd, the 1234 templature is 43 degrees.

# 使用序號格式化參數(shù)   加序號,從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位小數(shù))"
print(s2.format(pi = pi))
# PI是圓周率,值為3.141592653589793(保留2位小數(shù))

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

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

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

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

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

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

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

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

'''

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

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI