Python ---008--字串

來源:互聯網
上載者:User

標籤:字串

·字串

字串是一種資料類型,所有系統都支援字串
Windows,Linux,Nginx
Java c C++ C#

1、建立字串

s=‘Hello World‘s="Hello World"

2、支援分區操作

s=‘Hello World‘print sprint s[0:5]# 返回Helloprint s[:5] # 返回Hello

3、沒有字元,‘h‘,"h" 都是一樣 ,沒有字元與字串的區別 就是一個字串

訪問單個字元

print s[1] #e  同列表一樣

4、字串不可修改

s1=s[0:5]s2=s[5:11]s3=s1+‘PYthon‘+s2

5、操作符:

拼接操作符:"+"重複操作符:"*"關係操作符:< ><= >=邏輯操作符: and or not  成員操作符:in / not in 

·常用方法

help()

1、captalize()返回首字元大寫後的字串

s=‘hello‘print s.capitalize()  #Hello

2、casefold()返回字串所有小寫字串返回#python3版本

3、center(width)置中(width:填補空格數量)

s=‘hello‘print s.center(20)#hello置中在width數量空格

4、count(sub):返回sub 中出現字串數量

s=‘hello‘print s.count(‘l‘) #返回2count(sub,start,end)s=‘hello world‘print s.count(‘o‘,6,11) #返回1print s.count(‘o‘,4,11)#返回2

5、encode(encoding=‘UTF-8‘)

以指定的編碼格式對字串進行編碼

6、endswidth(str)
返回以str結尾的布爾值

s=‘hello‘print s.endswidth(‘a‘)#Falseprint s.endswidth(‘o‘)#True

7|、expandtabs(tablesize)
把字串中的tab 轉換成空格(預設tablesize=8)
\t 轉義為tab (長度取決於tablesize)

s=‘Hello\tWorld‘print sprint s.expandtabs(16)    #Hello   有16 個空格       World

8、find(sub )
尋找sub在字串中第一個出現的索引值,找不到返回-1

s=‘hello‘print s.find(‘e‘)#返回 1 下標print s.find(‘v‘)#返回-1 沒有這個字print s.find(‘a‘,3,5)#從3下標到5 下標出現a的下標

9、isalum(sub):
如果字串所有的字元都是字母或者數字,返回True,否則返回False

10、isalpha():
判斷是否字元

·格式化字串

按照統一的格式輸出字串

format()
1、傳遞一個replacement的欄位{}表示一個欄位

    ‘{0} love {1}‘.format(‘I‘,‘Baidu‘)#‘I love Baidu‘用{}表示欄位,數字表示位置,format方法對傳進來參數進行格式化處理

2、用字母代表位置

‘{a} love {b}‘.format(a=‘I‘,b=‘Baidu‘)#‘I love Baidu‘

3、如果既想用字母代表位置,又想用數字代表位置()

‘{0} love {b}‘.format(‘I‘,b=‘Baidu‘)#‘I love Baidu注意:位置參數必須在關鍵字參數在前,第一個關鍵字定義後,編譯器認為後面的參數都是按照關鍵字參數‘{a} love {0}‘.format(a=‘I‘,‘Baidu‘)#返回錯誤

4、在字串中列印‘{}’
所有{}必須接收參數,如果出現需要打的{},需要轉義
print ‘{{{0}}}‘.format(‘hehe‘)#‘{hehe}‘

‘{{{0}}} love {1}‘.format(‘I‘,‘Baidu‘)#‘{I} love Baidu‘

·字串的操作符

1、%c:格式化字元和ASCII碼

        print(‘%c‘ %65)#返回A        print(‘%c‘  %97)#返回a

2、%s:格式化一個字串

    print(‘%s Love Baidu‘ %‘I‘ )#I Love Baidu

3、%d:格式化整數

    print(‘%d‘%100) #100

4、%o:格式化無符號八位元

    print (‘%o‘%10)#十進位轉八進位 12

5、%x:格式化無符號十六進位數
6、%X:格式化無符號十六進位數(大寫)
7、%f:格式化定點數(浮點數),可以指定小數後的精度
不指定預設6位小數

    print (‘%f‘ %3.14) #3.1400008、%e:利用科學計數法格式化定點數(浮點數)    print (‘%e‘ %378.1415926)#3.781416e+029、%E同上只是大小寫不同10、%g:根據值的大小,自動選擇使用%e還是%f11|%G:同上只是大小寫不同

Python ---008--字串

聯繫我們

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