Python字符串
字符串或串(String)是由數字、字母、下劃線組成的一串字符。
一般記為 :
s="a1a2???an"(n>=0)
它是編程語言中表示文本的數據類型。
python的字串列表有2種取值順序:
比如:
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!Hllollo World!Hello World!Hello World!Hello World!TEST
Python比較運算符
以下假設變量a為10,變量b為20:
以下實例演示了Python所有比較運算符的操作:
#!/usr/bin/pythona = 21b = 10c = 0if ( 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 bLine 2 - a is not equal to bLine 3 - a is not equal to bLine 4 - a is not less than bLine 5 - a is greater than bLine 6 - a is either less than or equal to bLine 7 - b is either greater than or equal to b
新聞熱點
疑難解答
圖片精選