Python就將所有的英文單詞首字母變成大寫

2022-10-04 13:09:24 字數 1700 閱讀 2964

摘要:

將英文單詞首字母變成大寫是乙個古老的話題,很常用,也很簡單。不過如何用更簡單的方式批量完成這個工作,則有很多學問,不想來看看嗎!

將英文單詞首字母變成大寫是非常常用的文字操作,使用capitalize方法可以將乙個英文單詞的首字母變成大寫。但如何將一段文字中所有英文單詞的首字母都變成大寫呢?

最容易想到的方法是將這些英文單詞拆成獨立的單詞,然後分別使用capitalize方法將這些英文單詞的首字母變成大寫,然後再將這些單詞連線起來,實現**如下:

s = 'the weather is really nice today, very suitable for an outing.'

arr = s.split()

for i in range(0, l程式設計客棧en(arr)):

arr[i] = arr[i].capitalize()

s1 = " ".join(arr)

print(s1)

執行**看看效果:

the weather is really nice today, very suitable for an outing.

從這段**可以看出,使用了3個方法:split、capitalize和join。分別用來拆分字串;將英文單詞首字母轉換為大寫;使用特定的分隔符(本例是空格)合併列表中的字串。

不過這段**好麻煩,有沒有更簡單的方式呢?當然有,鐺鐺鐺!剛出鍋的**來了:

s = 'the weather is really nice today, ve程式設計客棧ry suitable for an outing.'

print(" ".join([word.capitalize() for word in s.split()])) # 只用了一行**

夠酷吧,這裡只用了一行**。其實這行**與前面的實現方法沒有本質的區別,只是用了python中通過for in語句生成列表的方式,將多行**簡化成了一行**,python簡直太神奇了。

其實啊,如果要熟悉python api,連一行**都不用寫,乙個方法就解決了,這就是string.capwords方法,該方法屬於string模組,所以需要先導入string模組,**如下:

import string

s = 'the weather is really nice today, very suitable for an outing.'

print(string.capwords(s)) #將字串中所有單詞首字母大寫

看看簡單不,別忙,還沒完呢!capwords方法的預設分隔符是空格,如果這些英文單詞用其他符號分隔,就需要使用capwordwww.cppcns.coms方法的第2個引數了,看下面的例子:

import string

s = 'the,weather,is,really,nice,today,very,suitable,for,an,outing.'

print(string.cap程式設計客棧words(s, ',')) # 用逗號分隔的英文單詞

這段**使用capwords方法將由逗號(,)分隔的所有英文單詞的首字母轉換為大寫字母。執行結果如下:

the,weather,is,really,nice,today,very,suitable,for,an,outing.

另外,做一下預告,最近要推出一系列文章,專門介紹python的核心api,本文是這一系列文章的第篇。掌握這些api的使用方法,可以讓我們少寫很多**,而且還會降低**的出錯機率!

總結

python 統計 英文 單詞

import sys,os,re def count words text num char text re.sub w text number text re.sub 0 9 text shrink whitespace text re.sub s text return text.count d...

Python常用英文單詞

一 互動式環境與print輸出 1 print 列印 輸出 2 coding 編碼 3 syntax 語法 4 error 錯誤 5 invalid 無效 6 identifier 名稱 識別符號 7 character 字元 二 字串的操作 1 user 使用者 2 name 姓名 名稱 3 at...

Python常用英文單詞

一 互動式環境與print輸出 1 print 列印 輸出 2 coding 編碼 3 syntax 語法 4 error 錯誤 5 invalid 無效 6 identifier 名稱 識別符號 7 character 字元二 字串的操作 1 user 使用者 2 name 姓名 名稱 3 att...