春季来好快,悄无声息不知不觉中,草儿绿了,枝条发芽了,遍地野花油菜花开灿烂多姿,一切沐浴着春晨曙光,春风中摇弋轻摆,仿佛少女轻歌曼舞,楚楚动人。
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
到此这篇关于Python入门学习之字符串与比较运算符就介绍到这了。生活就像海洋,只有意志坚强的人,才能到达彼岸。更多相关Python入门学习之字符串与比较运算符内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!