一、python怎么比较两个字符串相等?
直接用==比较
if "相等"=="相等":
print(”相等")
else:
print("不等")
代码如下:
str1='ab'
str2='ba'
str3='ab'
print 'str1==str2:',str1==str2 //false
print 'str1==str3:',str1==str3 //true
print 'str2==str3:',str2==str3, //false
Java怎么比较两个字符串相等?
str1.equls(str2) ,可以查看我之前关于字符串的博文,点击打开链接
Python有两种方法可以测试相等性:
1、 == 操作符测试值得相等性。Python运行相等测试,递归地比较所有的内嵌对象。(比较内容是否相等)
2、 is 表达式测试对象的一致性。Python测试二者是否是同一个对象。(比较内存地址是否相同)
例如:
lst1 = [1,2,3,4,[5,6]]
lst2 = [1,2,3,4,[5,6]]
lst3 = lst1
print 'lst1 == lst2\t',lst1 == lst2 # 内容相等
print 'lst1 is lst2\t',lst1 is lst2 # 内存地址不相同
print 'lst3 is lst1\t',lst3 is lst1 # 内存地址相同
-------------- result start -------------------------
lst1 == lst2 True
lst1 is lst2 False
lst3 is lst1 True
-------------- result end -------------------------
例外:
str1 = 'hello'
str2 = 'hello'
print str1 == str2
print str1 is str2
-------------- result start -------------------------
str1 == str2 True
str1 is str2 True
-------------- result end -------------------------
这里两个截然不同的对象碰巧有着相同的值, == 应该为True,is应该为False。但是这里都是True。为什么呢?因为python内部暂时存储并重复使用“短字符串”作为一种“最佳化”的优化方式。事实上,内存里面只有一个'hello'字符串,被str1和str2共享使用。为了得到一个更一般的结果,请看下例:
例如:
str3 = 'hello' * 10 #重复10个hello
str4 = 'hello' * 10 #重复10个hello
print 'str3 == str4\t', str3 == str4
print 'str3 is str4\t', str3 is str4
-------------- result start -------------------------
str3 == str4 True
str3 is str4 False
-------------- result end -------------------------
reaCode = None
if ( reaCode == None ):
print "is null"
else :
print "not!"
if ( reaCode is None ):
print "is null"
else :
print "not!"
reaCode = ''
if ( reaCode is '' ):
print "is null string"
else :
print "not!"
reaCode = ''
if ( reaCode == '' ):
print "is null string"
else :
print "not!"
if ( reaCode == None ):
print "is null"
else :
print "not!"
if ( reaCode is None ):
print "is null"
else :
print "not!"
None是一个空的对象,代表什么都没有。
而'',是一个字符串对象,代表一个空的字符串。
三、
空行也就是只有换行符
i = 0
For line in open('file.txt').readlines():
if line=='\r\n':
i = i + 1
print i
Java中的空行是readLine().equals("")
在python中处理空行时,经常会遇到一些问题。现总结经验如下:
1.遇到的空行如果只有换行符,直接使用=='\n'或者 len(line)==line.count('\n')
2.有多个空格+换行符时。有几种处理方法:①split; ②正则表达式'^\n'(不会);③if eachLine[:-1].strip()
展开:
eg.文件过滤,显示一个文件的所有行,忽略以井号(#)开头的行。
①
1 f=open('test.txt','r')
2 for eachLine in f:
3 if not eachLine.split(): # whether space
4 print eachLine,
5 elif eachLine.strip()[0]!='#':
6 print eachLine,
7
8 f.close()
1 f=open('test.txt','r')
2 for eachLine in f:
3 if not eachLine[:-1].strip():#whether space
4 print eachLine,
5 elif eachLine.strip()[0]!='#':
6 print eachLine,
7
8 f.close()
这两种方法都可以判断,
从同一台电脑上读取同样多行的字母,相对来说,第一种方法花费了8.4s,第三种方法花费了1.6s。从实验的角度上大概是第三种方法相对性能更优。
但具体是split()性能更优还是[:-1].strip()性能更优,有待进一步学习。