2014年7月3日 星期四

[Python] 變更字串內容

        
        今天在跟CAVEEducation的實習生介紹python入門的時候,提到一個概念"字串就是陣列",所以在操作字串的時候例如for迴圈或索引值(如[1:4])的時候都跟陣列操作的方式一樣。但是有個概念卻沒有說清楚。就是"無法修改字串中的元素"。


        例如如果我想這樣做:

text = "AbCdEf"
text[0] = "1"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-639914bf643c> in <module>()
1
2 text = "AbCdEf"
----> 3 text[0] = "1"
TypeError: 'str' object does not support item assignment
view raw gistfile1.py hosted with ❤ by GitHub
會出現錯誤訊息:TypeError: 'str' object does not support item assignment

那要如何針對字串內的東西做修改呢?
第一種方法:建立新的空字串,把修改的東西放回去


text = "AbCdEf"
text1 = ""
for i in range(len(text)):
if i == 0:
text1 += text[i].lower()
else:
text1 += text[i]
print text1
# abCdEf
view raw gistfile1.py hosted with ❤ by GitHub
這個做法就能針對字串的首字做大小寫的轉換

第二種方法更為簡潔:將字串轉成真的LIST物件,修改好之後再轉回字串

>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'
view raw gistfile1.py hosted with ❤ by GitHub

參考資料:http://stackoverflow.com/questions/1228299/change-one-character-in-a-string-in-python


不好意思誤導大家!

圖片來源:http://www.python-course.eu/variables.php


沒有留言:

張貼留言