| 函数 | 描述 |
|---|---|
| 字符串 | 不可变 |
| s1 += s2 | s1不在有引用,会扩大buffer,不新建字符串对象 |
| 切片 | 支持 |
| 去除空格 | strip , lstrip, rstrip |
| 拼接 | '.'.join(str) |
| 格式化 | '{}'.format(a) |
- Python 中字符串使用单引号、双引号或三引号表示,三者意义相同,并没有什么区别。其中,三引号的字符串通常用在多行字符串的场景。
- Python 中字符串是不可变的(前面所讲的新版本 Python 中拼接操作’+='是个例外)。因此,随意改变字符串中字符的值,是不被允许的。
- Python 新版本(2.5+)中,字符串的拼接变得比以前高效了许多,你可以放心使用。Python 中字符串的格式化(string.format)常常用在输出、日志的记录等场景。
字符串
- 字符串为常量对象
- 字符串赋值给变量,实则是变量指向字符串的内存地址,字符串对应的引用计数+1
s1 = '123'
s2 = '123'
print('s1 id is {}'.format(id(s1)))
print('s2 id is {}'.format(id(s2)))
#新建字符串
s2 = s2 + '4'
print('s1 id is {}'.format(id(s1)))
print('s2 id is {}'.format(id(s2)))
字符串常用操作
切片
s3 = 'abcdefg'
print(s3[:3])
print(s3[3:-1])
拼接
s1 += s2
Python 首先会检测 s1 还有没有其他的引用。如果没有的话,就会尝试原地扩充字符串 buffer 的大小,而不是重新分配一块内存来创建新的字符串并拷贝。这样的话,上述例子中的时间复杂度就仅为 O(n) 了。
string.join(iterable)
s5 = '123'
l = '.'.join(s5)
print(l)
strip去空格
s4 = ' 123 456 '
print(str.lstrip(s4))
print(str.rstrip(s4))
print(str.strip(s4))







网友评论