標籤:使用 函數 子串 this rip ima http ges tran
本文介紹了字串兩種重要的使用方式:字串格式化和字串方法。
一.字串格式化
二.字串方法
常用的字串方法有:find,join,lower,replace,split,strip,translate。
具體的代碼見下面
py檔案
# -*- coding: utf-8 -*-
#字串格式化
#1.簡單轉換
print ‘%s plus %s equals %s‘%(1,2,3)
from math import pi
print ‘Pi:%f...‘%pi
#2.欄位寬度和精度
print ‘%10f‘ % pi # 3.141593 欄位寬10
print ‘%10.2f‘ % pi # 3.14欄位寬10,精度2
print ‘%.5s‘ %‘abcdefgh‘ #abcde
print ‘%.*s‘ %(5,‘abcdefgh‘) #*號
#3.符號、對齊和用0填充
print ‘%010f‘ %pi #003.141593 在寬度精度前放一個標誌,可以是0,加,減號或空格,用於填充
print ‘%+10f‘ %pi # +3.141593 加號,用於標誌符號
print ‘%-10f‘ %pi #減號,靠左對齊
print (‘%+10f‘ %pi)+‘\n‘+‘%+10f‘ %-pi # +3.141593 換行 -3.141593,靠左對齊
#字串方法
#1.find:尋找子串,返回最左端索引,沒有返回-1
A=‘I am a student‘
print A.find(‘am‘) #2
print A.find(‘stu‘) #7
print A.find(‘su‘) #-1
#2.join:split的逆方法,用來串連序列中的元素
seq=[‘1‘,‘2‘,‘3‘,‘4‘,‘5‘]
a=‘+‘
print a.join(seq) #1+2+3+4+5 注意順序,不是seq.join(a)
#3.lower:返回字串的小寫字母片
print ‘AJDOEDD‘.lower()
#4.replace :返回某字串的所以匹配項均被替換後的字串
print ‘A and Hong are friends‘.replace(‘A‘,‘Ming‘)
#5.split join的逆方法,將字串分割成序列
print ‘1+2+3+4+5‘.split(‘+‘) #[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]
#6.strip 返回去除兩側空格的字串(可以去除無意加上的空格)
print ‘ A is B ‘.strip() #A is B
#7.translate 替換字元中的某些部分,只處理單個字元,可同時進行多個替換
from string import maketrans
table =maketrans(‘AB‘,‘CD‘) #maketrans函數接受兩個參數:兩個等長的字串,效果如下
print ‘this is A and B‘.translate(table) #this is C and D
[python基礎(二)]字串方法