Python 字串操作方法大全

來源:互聯網
上載者:User

標籤:python


1、去除空格

strip(self, chars=None)

lstrip(self, chars=None)

rstrip(self, chars=None)


2、字串中的大小寫轉換

lower(self) 轉換為小寫 

upper(self) 轉換為大寫 

swapcase(self) 大小寫互換

capitalize(self) 首字母大寫

capitalize(self) 首字母轉換為大寫,其餘小寫

title(self) 單詞首字母轉換為大寫


3、尋找字串

find(self, sub, start=None, end=None) 尋找字串位置,找不到返回-1

index(self, sub, start=None, end=None) 尋找字串位置,找不到報錯

rfind(self, sub, start=None, end=None) 從右邊開始尋找

count(self, sub, start=None, end=None) 搜尋到多少個指定字元



4、字串對齊

rjust(self, width, fillchar=None) 取固定長度靠右對齊,左邊不夠空格補齊

ljust(self, width, fillchar=None) 取固定長度靠左對齊,右邊不夠空格補齊

center(self, width, fillchar=None)取固定長度中間對齊,左右不夠用空格補齊


5、字串判斷

isupper(self) 字串是否全大寫 

islower(self) 字串是否全小寫 

startswith(self, prefix, start=None, end=None) 是否已某字串開頭

endswith(self, suffix, start=None, end=None) 是否已某字串結尾

isalnum(self) 是否全為字母或數字

isalpha(self) 是否全字母

isdigit(self) 是否全數字


6、字串分割

split(self, sep=None, maxsplit=None) 按照某符號分割,預設空格


7、字串串連

join(self, iterable) 串連元組或列表

>>>var_list = [‘tom‘, ‘david‘, ‘john‘]

>>>a = ‘_‘

>>>print a.join(var_list)

>>>tom_david_john


8、tab鍵填充空格、tab用\t表示

expandtabs(self, tabsize=None)  tab鍵填充指定數量空格


9、字串替換

format(self, *args, **kwargs) 替換預留位置 {0} {1} ...

replace(self, old, new, count=None) 替換指定次數的old為new,從左開始


本文出自 “10893237” 部落格,請務必保留此出處http://10903237.blog.51cto.com/10893237/1973881

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.