python對字串切片__python

來源:互聯網
上載者:User
對字串切片

字串 'xxx'和 Unicode字串 u'xxx'也可以看成是一種list,每個元素就是一個字元。因此,字串也可以用切片操作,只是操作結果仍是字串:

>>> 'ABCDEFG'[:3]'ABC'>>> 'ABCDEFG'[-3:]'EFG'>>> 'ABCDEFG'[::2]'ACEG'

在很多程式設計語言中,針對字串提供了很多各種截取函數,其實目的就是對字串切片。Python沒有針對字串的截取函數,只需要切片一個操作就可以完成,非常簡單。 任務

字串有個方法 upper() 可以把字元變成大寫字母:

>>> 'abc'.upper()'ABC'

但它會把所有字母都變成大寫。請設計一個函數,它接受一個字串,然後返回一個僅首字母變成大寫的字串。

提示:利用切片操作簡化字串操作。 ?不會了怎麼辦

取除首字母外的字串用[1:]

參考代碼:

def firstCharUpper(s):    return s[0].upper() + s[1:]print firstCharUpper('hello')print firstCharUpper('sunday')print firstCharUpper('september')

聯繫我們

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