今天遇到一點小問題,需要編寫一個程式將List 中的無規則英文名按【首字母大寫其餘部分小寫】的方式轉換
#一開始的思路是編寫一個函數將每個名字字串【str】進行處理,如何用map進行批次處理
不得不說,大方向的思路是正確的,但在細節的處理上出了些問題
一開始我是這樣寫名字處理函數的:
[python] view plain copy def change (name) result = name[0].upper() for a in name[1:len(name)]: result = result + a.lower()
然後運行會報錯
[python] view plain copy E:\PythonFile>python practice.py File "practice.py", line 6 for a in name(1:len(name)-1) : ^ SyntaxError: invalid syntax E:\PythonFile>python practice.py Traceback (most recent call last): File "practice.py", line 11, in <module> name_li = map (change, name_list) File "practice.py", line 6, in change for a in name(1,len(name)-1) : TypeError: 'str' object is not callable E:\PythonFile>python practice.py Traceback (most recent call last): File "practice.py", line 9, in <module> name_li = map (change, name_list) File "practice.py", line 5, in change name[0] = name[0].upper() TypeError: 'str' object does not support item assignment E:\PythonFile>python practice.py Traceback (most recent call last): File "practice.py", line 10, in <module> name_li = map (change, name_list) File "practice.py", line 6, in change name[0] = tmp TypeError: 'str' object does not support item assignment E:\PythonFile>python Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> l = 'zxcv' >>> print l[0] z >>> print l[0].upper <built-in method upper of str object at 0x02148740> >>> print l[0].upper() Z >>> z Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'z' is not defined >>> ^Z E:\PythonFile>python practice.py Traceback (most recent call last): File "practice.py", line 9, in <module> name_li = map (change, name_list) File "practice.py", line 6, in change name[0] = tmp TypeError: 'str' object does not support item assignment E:\PythonFile>python practice.py Traceback (most recent call last): File "practice.py", line 13, in <module> name_li = map (change, name_list) File "practice.py", line 5, in change tmp = chr(name[0]) TypeError: an integer is required
試過幾次後發現大致意思是對字串的處理不能這麼做,於是查了upper()和lower()的用法,發現這兩個函數就是直接作用在str的,所以根本不需要這麼麻煩。
修改後:
[python] view plain copy # practice.py # Change the first char in every name from lower type to upper type def change (name): result = name[0:1].upper()+name[1:len(name)].lower() return result name_list = ['kzd','ysy','kcw','scr','ky'] name_li = map (change, name_list) print name_l
運行結果:
[python] view plain copy E:\PythonFile>python practice.py ['Kzd', 'Ysy', 'Kcw', 'Scr', 'Ky']
錯誤在於我企圖將字串中的元素賦值替換,這是不允許的。
【相關推薦】
1. Python免費影片教學
#3. python中轉換大小寫的方法
以上是詳解python中lower和upper函數的使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!