python字符串搜索

python字符串字串查找 find和index方法

更多0

python 字符串查找有4个方法,1 find,2 index方法,3 rfind方法,4 rindex方法。

1 find()方法:查找子字符串,若找到返回从0开始的下标值,若找不到返回-1

info = 'abca'print info.find('a')##从下标0开始,查找在字符串里第一个出现的子串,返回结果:0

info = 'abca'print info.find('a',1)##从下标1开始,查找在字符串里第一个出现的子串:返回结果3

info = 'abca'print info.find('333')##返回-1,查找不到返回-1

2 index()方法:

python 的index方法是在字符串里查找子串第一次出现的位置,类似字符串的find方法,不过比find方法更好的是,如果查找不到子串,会抛出异常,而不是返回-1

info = 'abca'print info.index('a')print info.index('33')


str = "Line1-abcdef 
Line2-abc 
Line4-abcd";print str.split( );print str.split(' ', 1 );

以上实例输出结果如下:

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']

split()输出的为一个list

python list 怎么查出一个元素的所有位置

专业回答
2014-03-18 19:48
list的index(object)返回 元素第一次出现的位置


a = ["ab","cd",1,3]
print a.index(1)
输出就是2

for i in range(3,0,-1):
print i
3
2
1
  • if/elif/else、try/except/finally、for/while

[python] view plain copy
 print?
  1. while True:  
  2.     newvar=8  
  3.     print(newvar)  
  4.     break;  
  5.   
  6. print(newvar)  
  7.   
  8. try:  
  9.     newlocal=7  
  10.     raise Exception  
  11. except:  
  12.     print(newlocal)#可以直接使用哦  

输出结果:8 8 7

可见这个关键字中定义变量,他们的作用域跟外部是一致的,这个跟Java的作用域概念有点不一样。


http://blog.csdn.net/lovingprince/article/details/6627555




原文地址:https://www.cnblogs.com/wuqingzangyue/p/5770106.html