Python的序列类型——字符串
一、字符串的误解
计算机系统的每个内存单元都是唯一并且连续的物理地址,字符串在内存中一旦创建就被操作系统分配一块唯一并且连续的地址。计算机系统不允许我们修改字符串中的内容,一旦我想试图进行修改,系统马上报错。但如果我们想修改其中的内容,计算机系统会为我们开辟一块新的内存空间。
例如:newstring是新生成的内存
oldstring = “周杰伦的烟花易冷”
newstring = oldstring. replace(‘周杰伦’, ’林志炫’)
例如:string是新生成的内存
string_1 = "abc" string _2 = "def" string = string _1 + string _2
注:上面两个例子,oldstring 和string 的值并没有改变,string的意示图如下:
二、几个常用的函数
1. join(...)函数
参数...为要连接的元素序列,该方法常用于往字符串中间插入字符串。用法如下:
oldstring = "成熟是一种明亮而不刺眼的光辉" newstring = " ".join(oldstring) print(newstring) #输出:成 熟 是 一 种 亮 而 不 刺 眼 的 光 辉
2. split(...)函数
将参数作为分隔符,可指定分隔的次数,但自己匹配的参数无法出现才结果集中,该函数常用与
不需要自己匹配的参数的运算中,用法如下:
string = "5+10" value_1,value_2 = string.split('+') value = int(value_1) + int(value_2) print(value) #输出:15
3. maketrans函数 和 替换函数
maketrans(x, y=None, z=None, /) 、 translate(...) 和 replace()。maketrans函数用于建立键值对的映射,而替换函数translate函数和replace函数的使用各有千秋。下面将用一个例子来说明的他们的作用。
例如:使maketrans 与 translate的结合
string = "abcdefghijk" setKY = str.maketrans("abcd","----") #Set built-in print(string.translate(setKY)) #输出:----efghijk
例如:replace的使用
string = "abcdabcdabcdabcd" print(string.replace("ab",'--',2)) #参数2表示替换目标序列的前两个子序列 print(string.replace("ac",'--',2)) #替换无效,还是原样输出
4. expandtabs(...)函数
使用该函数将指定的n个字符为单位,当字符对象不足n个字符时,自动为对象字符填充剩余的空格。例如:
test = “username\temail\tpassword\nLynnLee\t [email protected]\t123\n nLynnLee\t [email protected]\t123\n” v = test.expandtabs(20) print(v) 结果为: username email password LynnLee [email protected] 123 nLynnLee [email protected] 123
三、其他常用函数总结