常见的String类型用法其实Python的String类型和其它的语言都很类似,可以这样定义a="Alex"或者a="Alex"可以字符串叠加,可以与整形之间相互转化,例如定义a="6" b=4+int(a),这个就相当于C#中的强制转化,很Easy的。__author__="Alex" __date__ ="$2011-2-17 10:39:27$" if __name__ == "__main__": print "Hello"; a = "Alex" b = "Viki" ab = a+b # ab becomes "AlexViki" print(ab) a += " Lu" # a becomes "Alex Lu" print(a) b = "She " + "is " + "my gf " + b + " Shao" # b becomes "She is my gf Viki Shao" print(b) c = 5 print(c) d = "a" + str(c) # adding a number value to a: d becomes "a5" print(d) e = "8" # creating a string with only a number f = 3 + int(e) # f becomes the integer 11 print(f)运行结果:Hello AlexViki Alex Lu She is my gf Viki Shao 5 a5 11特殊字符大家都知道每种语言都有自己的保留关键字,还有一些其它的如“”之类的特殊符号,如果你要输出这些字符,该如何做呢,很简单,对,没错,反斜杠转义。Show代码:__author__="Alex" __date__ ="$2011-2-17 10:39:27$" if __name__ == "__main__": print "Hello"; print( "Hi, how are you?
I"m fine
What"s your name?
My name is "Alex.lu"" )很简单的,运行结果,会识别
为换行符," 会识别为“输出:Hello Hi, how are you? I"m fine What"s your name? My name is "Alex.lu"substring一个字符串会包含很多字符,那么我们在使用的时候会把它当做一个数组来使用,利用define a="Alex.lu" 那么a[0:1]就代表着第一个字母A,a[1:3]就意味着第二个字符和第三个字符也就是lx,而用负数则表示从后面开始计算,a[-1] 就代表u,看代码吧:__author__="Alex" __date__ ="$2011-2-17 10:39:27$" if __name__ == "__main__": print "Hello"; a="Alex.lu" print(a[0:1]) print(a[1:3]) print(a[-1]) print(a[-3:-1])运行结果:Hello A le u .l字符串操作方法:字符串有很多操作方法,如果你使用和我一样的编辑器(netbeans),你会很容易的像使用VS,或者Eclipse一样看到很多方法,在下面的程序中只是列举了一些常用的方法,更多的方法需要我们在使用的过程中去发现:__author__="Alex" __date__ ="$2011-2-17 10:39:27$" if __name__ == "__main__": print "Hello"; a = " Alex " print(a.strip()) # returns "Alex" print(a.lstrip())# returns "Alex " print(a.rstrip()) # returns " Alex" b = "hi!!!!" print(b.rstrip("!")) # returns "hi" print(b.count("!")) # returns 4 c = "Alex.lu@csdn.com" print(c.split("@")) # returns a list: ["Alex.lu","csdn.com"] print(c.split("@")[0]) # returns "Alex.Lu" d = "Alex" e = "Viki" print(d.upper()) # returns "ALEX" - this method can be used for case insensitive testing print(e.upper()) # returns "VIKI" print(d.lower()) # returns "alex" print(e.lower()) # returns "viki"对照返回结果和我的注释,聪明的你就知道这些方法是做什么用的了:Hello Alex Alex Alex hi 4 ["Alex.lu", "csdn.com"] Alex.lu ALEX VIKI alex viki