字符串类型是Python里面最常见的类型。我们可以通过在引号(‘ 和 “ 的作用是一样的)间包含字符的方式创建它。字符串是一种标量,而且是不可变类型。字符串是由独立的字符组成的,这些字符可以通过切片操作顺序的访问。
<span style="font-size:14px;">>>> aStr = 'hello world' >>> another = "hello csdn" >>> aStr 'hello world' >>> another 'hello csdn' >>> s = str(range(5)) >>> s '[0, 1, 2, 3, 4]' >>> </span>
Python中没有字符这种类型,而是用长度为1的字符串来表示。用切片操作可以得到字符或子串。
<span style="font-size:14px;">>>> aStr 'hello world' >>> aStr[2] 'l' >>> aStr[2:] 'llo world' </span>
你可以通过给一个变量重新赋值来改变字符串。
<span style="font-size:14px;">>>> aStr 'hello world' >>> aStr = aStr[:6] + ' python' >>> aStr 'hello python' >>> </span>
字符串是不可变的,所以你不可以删除一个字符串的某个字符,你能做的就是把整个字符串都删除。若你想达到删除某个字符的效果,可以把剔除了不需要部分的字符串组合起来成为一个新串。比如我要删掉‘o’,可以通过del语句来删除字符串。
<span style="font-size:14px;">>>> aStr = 'hello man' >>> aStr = aStr[:4] + aStr[5:] >>> aStr 'hell man' >>> del aStr </span>
<span style="font-size:14px;">>>> str1 = 'abc' >>> str2 = 'def' >>> str3 = 'kmn' >>> str1 < str2 True >>> str1 != str2 True >>> str1 < str3 and str2 == 'def' True >>> </span>字符串之间是按照ASCII值得大小来比较的。
<span style="font-size:14px;">>>> str = 'abcdefg' >>> str[0:3] 'abc' >>> str[2:5] 'cde' >>> </span>逆向索引:
<span style="font-size:14px;">>>> str[-6:-1] 'bcdef' >>> str[-8:-1] 'abcdef' >>> </span>
<span style="font-size:14px;">>>> str[:4] 'abcd' >>> str[4:] 'efg' >>> str[:] 'abcdefg' >>> </span>
<span style="font-size:14px;">>>> 'bc' in 'abcd' True >>> 'n' in 'abcd' False >>> 'dd' not in 'abcd' True >>> </span>
<span style="font-size:14px;">>>> 'this is str1' + ' this is str2' 'this is str1 this is str2' >>> s = 'xxx' + ' ' + 'is a good' + ' ' + 'student' >>> s 'xxx is a good student' </span>
<span style="font-size:14px;">>>> text = 'hello' 'world!' >>> text 'helloworld!' >>> </span>
原文:http://blog.csdn.net/u012088213/article/details/44656051