(自興人工智慧)python字串

來源:互聯網
上載者:User

標籤:資料   匹配   strip   case   lower   class   16px   font   style   

字串是python中最常用的資料類型,我們可以使用單引號(‘ ‘)或雙引號(" ")來建立字串。

a=‘Hello‘b="Hello"

所有標準序列操作如(索引,分區,成員資格,求長度,取最小值和最大值等),對字串同樣適用。

字串常用的格式化符號:

(%s 格式化字串)

print(‘Hello,%s‘%‘world‘) #使用%s作為‘world‘的預留位置Hello,world #結果print(‘還有%s天‘%10) #使用%d作為10的預留位置還有10天 #結果#%s不僅可以格式化字串,還可以格式化整數

(%d 格式化整數)

print(‘還有%d天‘%10) #使用%d作為10的預留位置還有10天 #結果

 字串常用的方法:

find():用於檢測字串中是否包含子字串str,可以指定開始和結束的範圍。

a=‘hello,world‘print(a.find(‘wo‘))6 #返回了匹配值的索引print(a.find(‘kb‘))-1 #找不到,返回-1
print(a.find(‘wo‘,3)) #提供起點6 #結果print(a.find(‘wd‘,6))-1 #結果
print(a.find(‘wo‘,3,8)) #提供起點和終點6 #結果print(a.find(‘wd‘,3,7))-1 #結果

lower():將字串中所有大寫字元轉換為小寫

a=‘HeLlo‘b=a.lower()print(b)hello #結果

upper():將字串中所有小寫字元轉換為大寫

a=‘HeLlo‘b=a.upper()print(b)HELLO #結果

swapcase():將字串中所有小寫字元轉換為大寫,大寫字元轉換為小寫

a=‘HeLlo‘b=a.swapcase()print(b)hElLO #結果

replace():把字串中的舊字串替換成新字串

a=‘hello world‘b=a.replace(‘hello‘,‘HELLO‘)print(b)HELLO world #結果

strip():移除字串頭尾指定字元

a=‘++hello world++‘b=a.strip(‘+‘)print(b)hello world #結果b=a.strip(‘++h‘)print(b)ello world #結果b=a.strip(‘++d‘)print(b)hello worl #結果

 

(自興人工智慧)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.