Python 字串的操作

來源:互聯網
上載者:User

標籤:大寫   start   返回   ali   int   ndt   python   個數   使用   

字串的拼接
a = "hello"b = "klvchen"c = a + bprint(c)結果:helloklvchen

注意:該方法效率比較低,推薦使用 join 方法

a = "hello"b = "klvchen"c = " ".join([a, b])print(c)結果:hello klvchen
字串的各種方法

統計元素個數

str = "hello klvchen"print(str.count(‘l‘))             結果:3

首字母大寫

str = "hello klvchen"print(str.capitalize())結果:Hello klvchen

置中

str = "hello klvchen"print(str.center(50,‘#‘))結果:##################hello klvchen###################

判斷是否以某個內容結尾

str = "hello klvchen"print(str.endswith(‘chen‘))結果:True

判斷是否以某個內容開始

str = "hello klvchen"print(str.startswith(‘tt‘))結果:False

設定 tab 的 size

str = "hello \tklvchen"print(str.expandtabs(tabsize=30))結果:hello                         klvchen

尋找第一個元素,並返回索引

str = "hello klvchen"print(str.find(‘t‘))print(str.find(‘l‘))結果:-12

format

str = "hello {name}"print(str.format(name=‘klvchen‘))結果:hello klvchen

format_map

str = "hello {name} is {age}"print(str.format_map({‘name‘:‘klvchen‘,‘age‘:28}))結果:hello klvchen is 28

去除字串兩邊空格及tab

str = ‘ hello world ‘print(str.strip())結果:hello world

替換字串

str = ‘hello world‘print(str.replace(‘o‘, ‘a‘))             # 全部替換print(str.replace(‘o‘, ‘a‘, 1))         # 只替換一次結果:hella warld hella world 

切割字串

str = ‘hello world‘print(str.split(‘ ‘))結果:[‘hello‘, ‘world‘]

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.