1. 字符串索引
s = '<any string>'
s[0] 是字符串中第一个字符
s[-1]是字符串中最后一个字符
2. 抽取子字符串
<string>[<number>]: one-character string,得到字符串中位置为number的字符。
<string> [<expression_start> : <expression_stop>]
抽取得到的子字符串为原字符串从start位置开始到stop位置结束的字符串,且不包含stop位置上的字符。
即为原字符串中从start位置开始的字符到stop-1位置的字符。
<string>[start : ] :为字符串从start位置开始到字符串最后一个位置。
<string>[ : end] :为字符串从第一个位置到第end-1个位置的字符。
<string>[ : ] :为字符串从开始到结束,输出为原来的完整字符串。
3.<string>.find('target string')
如果找不到该字符串,则返回-1,找到则返回该目标字符串起始位置。
4.<string>.find(''),空字符串,将返回0。
<string>.find('taget string', start_position): 从start_position位置开始寻找目标字符串。
5.find_url
代码:
page =('<div id="top_bin"><div id="top_content" class="width960">'
'<div class="udacity float-left"><a href="http://udacity.com">')
start_link = page.find('<a href=')
start_quote = page.find('"',start_link)
end_quote = page.find('"',start_quote + 1)
url = page[start_quote + 1 : end_quote]
print url
输出结果: http://udacity.com
6. 关于单个字符串
s = 'a'
print s[1]
将出现错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
print s[1:-1]
不出现错误,打印出空字符串。此时s[1:-1]对应的为空字符串。