- 字符串是由字符組成的序列(sequnence),所以它是有序的。
TypeError: string indices must be integers
- 獲取最後一個字符
letter=word(len(word)-1)#但是記得減一,原因如上所述
last=word[-1]#返回最後一個字符,-2表示返回倒數第二個字符
使用負索引的時候,從-1到第一個字符,則索引的絕對值正好是從1到 字符串的長度。其實這個就比較好理解了。- 遍歷的話,既可以用while 也可以用for,for比較好用。
- 字符串切片(slice):切片表示的都是複製
[n:m]
操作符返回從第n個字符到第m個字符的字符串片段,(請注意這裏的第幾個,是從0開始算的)包括第一個,但是不包括最後一個。
這個行爲違反直覺,但是將指向兩個字符之間的索引, 想象成 下圖那樣或許有幫助。
>>> fruit = 'banana'
>>> fruit[0:5:2]
'bnn'
>>> 'word'[::-1]
'drow'
- 字符串是不可變的
word='hi girlfriend!'
word[4]='v'
TypeError: 'str' object does not support item assignment
- 搜索(search):
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
- 字符串方法
.upper()
>>> word = 'banana'
>>> new_word = word.upper()
>>> new_word
'BANANA'
.lower()
upper(word)
,
而是方法的語法 word.upper()
。返回一個都是大寫字母的新字符串。用點標記的形式支出方法的名字。空括號表示不接受實參.find('~')
>>> word = 'banana'
>>> index = word.find('a')
>>> index
1
>>> word.find('na')
2
.count
bytes.
count
(sub[, start[, end]])¶bytearray.
count
(sub[, start[, end]])
Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
'www.baidu.com'.count('w')
3
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.
.strip---去掉頭尾指定的字符串
strip()方法語法:
str.strip([chars]);
- chars -- 移除字符串頭尾指定的字符。
返回移除字符串頭尾指定的字符生成的新字符串。
.split---分隔
split()方法語法:
str.split(str="", num=string.count(str)).
- str -- 分隔符,默認爲所有的空字符,包括空格、換行(\n)、製表符(\t)等。
- num -- 分割次數。
返回分割後的字符串列表。
.replace
bytes.
replace
(old, new[, count])bytearray.
replace
(old, new[, count])
Return a copy of the sequence with all occurrences of subsequence oldreplaced by new. If the optional argument count is given, only the first count occurrences are replaced.
The subsequence to search for and its replacement may be any bytes-like object.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- in運算符
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
- 字符串比較
'apple'<'banada'
True
'banada'<'apple'
False
'Banada'<'apple'
True
- 文字遊戲
>>> fin = open('words.txt')
fin
是輸入文件對象的一個常用名。該文件對象提供了幾個讀取方法,
包括 readline
,其從文件中讀取字符直到碰到新行,並將結果作爲字符串返回:
>>> fin.readline()
'aa\r\n'
此文件對象跟蹤它在文件中的位置, 所以如果你再次調用readline,你獲得下一個單詞:
>>> fin.readline()
'aah\r\n'
你也可以將文件對象用做for循環的一部分。 此程序讀取 words.txt
並打印每個單詞,每行一個:
fin = open('words.txt')
for line in fin:
word = line.strip()#strip是字符串方法,去掉空格
print(word)