Python入门学习之字符串与比较运算符
Python字符串
字符串或串(String)是由数字、字母、下划线组成的一串字符。
一般记为 :
s="a1a2···an"(n>=0)
它是编程语言中表示文本的数据类型。
python的字串列表有2种取值顺序:
- 从左到右索引默认0开始的,最大范围是字符串长度少1
- 从右到左索引默认-1开始的,最大范围是字符串开头
- 如果你的实要取得一段子串的话,可以用到变量[头下标:尾下标],就可以截取相应的字符串,其中下标是从0开始算起,可以是正数或负数,下标可以为空表示取到头或尾。
比如:
s = 'ilovepython'
s[1:5]的结果是love。
当使用以冒号分隔的字符串,python返回一个新的对象,结果包含了以这对偏移标识的连续的内容,左边的开始是包含了下边界。
上面的结果包含了s[1]的值l,而取到的最大范围不包括上边界,就是s[5]的值p。
加号(+)是字符串连接运算符,星号(*)是重复操作。如下实例:
#!/usr/bin/python # -*- coding: UTF-8 -*- str = 'Hello World!' print str # 输出完整字符串 print str[0] # 输出字符串中的第一个字符 print str[2:5] # 输出字符串中第三个至第五个之间的字符串 print str[2:] # 输出从第三个字符开始的字符串 print str * 2 # 输出字符串两次 print str + "TEST" # 输出连接的字符串
以上实例输出结果:
Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST
Python比较运算符
以下假设变量a为10,变量b为20:
以下实例演示了Python所有比较运算符的操作:
#!/usr/bin/python a = 21 b = 10 c = 0 if ( a == b ): print "Line 1 - a is equal to b" else: print "Line 1 - a is not equal to b" if ( a != b ): print "Line 2 - a is not equal to b" else: print "Line 2 - a is equal to b" if ( a <> b ): print "Line 3 - a is not equal to b" else: print "Line 3 - a is equal to b" if ( a < b ): print "Line 4 - a is less than b" else: print "Line 4 - a is not less than b" if ( a > b ): print "Line 5 - a is greater than b" else: print "Line 5 - a is not greater than b" a = 5; b = 20; if ( a <= b ): print "Line 6 - a is either less than or equal to b" else: print "Line 6 - a is neither less than nor equal to b" if ( b >= a ): print "Line 7 - b is either greater than or equal to b" else: print "Line 7 - b is neither greater than nor equal to b"
以上实例输出结果:
Line 1 - a is not equal to b Line 2 - a is not equal to b Line 3 - a is not equal to b Line 4 - a is not less than b Line 5 - a is greater than b Line 6 - a is either less than or equal to b Line 7 - b is either greater than or equal to b
赞 (0)