详解python中lower和upper函数的使用
生活随笔
收集整理的這篇文章主要介紹了
详解python中lower和upper函数的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天遇到一點小問題,需要編寫一個程序將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免費視頻教程
2. python基礎入門之upper簡介
3. python中轉換大小寫的方法
以上就是 詳解python中lower和upper函數的使用的詳細內容,更多請關注風君子博客其它相關文章!
總結
以上是生活随笔為你收集整理的详解python中lower和upper函数的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 递归求二叉树的深度_优雅地用堆栈替代递归
- 下一篇: 语音问答系统源码,收费语音问答(分答、值