python之路-------字串與Regex

來源:互聯網
上載者:User

標籤:python字串   python操作   

1.1、#####去掉字串中的轉義符string.strip()
print "hello\tworld\n"
>>> word="\thello world\n"
>>> print "word.strip()後輸出:",word.strip()
word.strip()後輸出: hello world
>>> print "word.lstrip()後輸出:",word.lstrip()
word.lstrip()後輸出: hello world

>>>
1.2、#####字串拼接使用+或者join
>>> str1="you "
>>> str2="and "
>>> str3="me"
>>> 
>>> 
>>> result=str1+str2+str3
>>> print result
you and me
##python提供了函數join()連接字串,join()配合列表實現多個字串的串連十分方便
>>> strs=[‘you ‘,‘and ‘,‘me‘]
>>> "".join(strs)
‘you and me‘
1.3、#####字串的截取,[start:end:step]從string的第start索引位置開始到第end個索引之間(不包括end)截取子串,截取的步長是step
##擷取偶數位的字元
>>> str1="hello world"
>>> print str1[1::2]
el ol
>>> print str1[1:3:2]
e

##split()使用
split([char][,num]):參數char表示用於分隔的字元,預設的分隔字元是空格;參數num表示分隔的次數,num+1個子串
>>> str1="yangsq said: 1, 2, 3, 4"
>>> str1.split()
[‘yangsq‘, ‘said:‘, ‘1,‘, ‘2,‘, ‘3,‘, ‘4‘]
>>> str1.split(‘,‘,2)
[‘yangsq said: 1‘, ‘ 2‘, ‘ 3, 4‘]
1.4、#####字串的比較
java使用equal()比較兩個字串的內容,python直接使用==、!=比較字串的內容,如果比較的兩個變數的類型不同,比較的內容自然不同
>>> str1,str2=1,"1"
>>> if str1!=str2:print "不相同"
... 
不相同
>>> if str(str1)==str2:print "相同"
... 
相同


##比較字串,可以比較截取的子串,也可以比較字串的開頭和結尾部分(使用startswith或endswith()函數)
1.5、#####字串的反轉
def reverse():
l1=list("hello")
out=‘‘
for i in range(len(l1),0,-1):
print("l1[i-1]->",l1[i-1])
out+=l1[i-1]
else:
print "out=%s" %out
print type(out)
>>> reverse()
(‘l1[i-1]->‘, ‘o‘)
(‘l1[i-1]->‘, ‘l‘)
(‘l1[i-1]->‘, ‘l‘)
(‘l1[i-1]->‘, ‘e‘)
(‘l1[i-1]->‘, ‘h‘)
olleh

python的列表是對字串進行處理的常用方式,靈活使用列表等內建資料結構處理字串,能夠降低編程的複雜度。利用序列的"切片"實現字串的反轉最為簡潔
>>> str1="hello"
>>> str1[::-1]
‘olleh‘
1.6、字串的尋找和替換
help(str.find):find(...) S.find(sub [,start [,end]]) -> int,如果找到字串sub,則返回源字串第1次出現的索引,否則返回-1
help(str.replace):replace(...) S.replace(old, new[, count]) -> string,replace實現字串的替換,該函數可以指定替換的次數,預設是替換所有匹配的old
>>> str1="hello world,hello china"
>>> print str1.replace("hello","hi")
hi world,hi china
>>> print str1.replace("hello","hi",1)
hi world,hello china

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

python之路-------字串與Regex

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.