- python中单引号
''
和双引号" "
相同,但不可混合
使用 - python中字符串
不能改变
,没有字符类型,一个字符就是长度为1的字符串 - 索引方式有两种,从左到右以0开始,从右往左以-1开始
- 字符串截取(切片)语法:
变量[头下标:尾下标]
(不包含尾下标的值)
>>> str1 = 'chinese'
>>> str1[3:7]
'nese'
>>> print('hello\nworld')
hello
world
>>> print(r'hello\nworld')
hello\nworld
- 占位符
语法:%[-w.p]type
-
表示左对齐,默认右对齐
w
表示宽度
p
表示精度
type
表示数据类型(d整型,f浮点型,s字符串) - format(py2.6)
语法:'{[:w.pf]}'.format(var)
w
表示宽度
pf
表示浮点数精度 - f-string(py3.6)
语法:f'{var[:w.pf]}'
w
表示宽度
`pf表示浮点数精度
>>> name = "小明"
>>> age = 10
>>> print ("我叫 %s 今年 %d 岁!" % (name, age))
我叫 小明 今年 10 岁!
>>> str1 = "{0}爱{1},{1}爱{0}"
>>> print(str1.format('我', '学习'))
我爱学习,学习爱我
>>> str = 'python'
>>> print(f"学习 {str}")
学习 python
函数 | 描述 |
---|
str.capitalize() | 将字符串首字母大写 |
str.count(sub, beg= 0,end=len(str)) | 子串sub出现次数 |
str.encode(encoding) | 编码 |
bytes.decode(encoding, ‘strict’) | 解码 |
str. swapcase() | 大写转小写,小写转大写 |
str.title() | 每个单词首字母大写 |
>>> str = 'chinese'
>>> str.capitalize()
'Chinese'
>>> str.count('e')
2
>>> str = '中国'
>>> bytes = str.encode('utf-8')
>>> bytes
b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> bytes.decode('utf-8')
'中国'