今天在跟CAVEEducation的實習生介紹python入門的時候,提到一個概念"字串就是陣列",所以在操作字串的時候例如for迴圈或索引值(如[1:4])的時候都跟陣列操作的方式一樣。但是有個概念卻沒有說清楚。就是"無法修改字串中的元素"。
例如如果我想這樣做:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
那要如何針對字串內的東西做修改呢?
第一種方法:建立新的空字串,把修改的東西放回去
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
text = "AbCdEf" | |
text1 = "" | |
for i in range(len(text)): | |
if i == 0: | |
text1 += text[i].lower() | |
else: | |
text1 += text[i] | |
print text1 | |
# abCdEf |
第二種方法更為簡潔:將字串轉成真的LIST物件,修改好之後再轉回字串
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> 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' |
參考資料:http://stackoverflow.com/questions/1228299/change-one-character-in-a-string-in-python
不好意思誤導大家!
圖片來源:http://www.python-course.eu/variables.php
沒有留言:
張貼留言