[python基礎(二)]字串方法

來源:互聯網
上載者:User

標籤:使用   函數   子串   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基礎(二)]字串方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.