【python基礎】之str類字串,pythonstr字串

來源:互聯網
上載者:User

【python基礎】之str類字串,pythonstr字串

str類字串是不可變對象

1.建立字串
s1 = str() #建立一個Null 字元串s2 = str("hello") #建立字串"hello" 

 

2.處理字串的常用函數和操作(1).函數
len() 返回一個字串的字元個數
max() 返回字串中最大的字元
min() 返回字串中最小的字元

>>>s = "Welcome">>>len(s)7>>>max(s)'o'>>>min(s)'W'

 

字串s全文通用,下面不再敘述

(2).下標運算子[ ]s[ index ] index 的範圍為 [ 0, len(s) - 1].注意:python中允許負數最為下標
>>>print(s[6], s[4])e o>>>print(s[-1], s[-3])e o

 


(3).截取運算子 [start:end][start:end] 截取並返回字串s中下標從start開始到end-1結束的一個字串,若start > end,則返回Null 字元串
>>>s[1:4]'elc'>>>s[1:-1] #也可以使用負數'elcom'>>>s[3:-8] #截取出現交叉返回Null 字元串''

 

 (4).串連運算子 + ,複製運算子 *+ :串連兩個字串。- :對字串進行複製
>>>s1 = "hello">>>s2 = "world">>>s1 + ' ' + s2'hello world'>>>3 * s1         #和s1 * 3 相同'hellohellohello'

 


(5).判斷一個字串是否在另一個字串中(in和not in)舉例:s是字串"Welcome"
>>>'come' in s  #若為真,則返回tureTrue>>>'cat' in s   #若為假,則返回falseFalse>>>'cat' not in sTrue

 


(6).比較字串(==, !=, >,<,,>=,<=)python通過字串中的字元進行比較。從第一個字元開始比較。若第一個字元相同,則比較第二個字元,以此類推。若運算式成立,則返回True,否則返回False
>>> s1 = 'integer'>>> s2 = 'int'>>> s1 == s2False>>> s1 < s2  # 'e' 的ARCII碼值大於0,所以返回falseFalse>>> s1 >= s2True

 

 (7).昳代字串(用for迴圈)yi代字串s:
>>> for ch in s:    print(ch)    Welcome>>> 
3.其他字串(1).測試字串
isalnum(): bool 如果這個字串是字母數字且至少有一個字元,則返回true
isalpha(): bool 如果這個字串是字母且至少有一個字元,則返回true
isdigit(): bool 如果這個字串中只含有數字字元則返回true
isdentifier(): bool    如果這個字串是python標識符則返回true
islower(): bool 如果字串中所有的字元全是小寫且至少有一個字元,則返回true
isupper(): bool 如果字串中所有的字元全是大寫且至少有一個字元,則返回true
isspace(): bool 如果字串中所有的字元全是空格且至少有一個字元,則返回true


(2).搜尋字串
startswitch(s1: str): bool 若字串是以子串是s1開始,則返回true
endswitch(s1: str): bool 若字串是以子串是s1結尾,則返回true
find(s1): int 返回s1在字串的最低下標,不存在則返回-1
rfind(s1): int 返回s1在字串的最高下標,不存在則返回-1
count(sub string): int 返回子串在字串中出現的無覆蓋次數
(3).轉換字串
capitalize(): str 返回複製的字串,並大寫第一個字元
lower(): str 返回複製的字串,並將所有的字母轉換為小寫
upper(): str 返回複製的字串,並將所有的字母轉換為大寫的
title(): str 返回複製的字串,並大寫每個單詞的首字母
swapcase(): str 返回複製的字串,並將大寫字母轉換為小寫,小寫字母轉換為大寫
replace(old, new): str 返回新的字串new,用new替換所有的舊字串old出現的地方
(4).刪除字串中的空格
lstrip(): str 返回去掉前端空白字串的子字串
rstrip(): str 返回去掉後端空白字串的子字串
strip(): str 返回去掉兩端空白字串的子字串
(5).格式化字串
center(width): str 返回在給定寬度域上置中的字串副本
ljust(width): str 返回在給定寬度域上靠左對齊的字串文本
rjust(width): str 返回在給定寬度域上靠右對齊的字串文本
format(items): str  


 

聯繫我們

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