- 字符串是由字符组成的序列(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)