computer science 101-unit1-python2字符串小结

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]对应的为空字符串。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值