索引
字符串的索引是只读,不能修改,从左到右的索引以0
开始,从右到左的索引以-1
开始(因为-0=0
程序无法识别左右)
1 2 3 4
| test = 'name' c1 = test[0] c2 = test[-1] c3 = test[-2]
|
截取
从字符串中获取子串,类似substring
之类的功能,也是以索引来获取。
格式为:字符串[头下标,尾下标]
,采用前闭后开的规则,表示截取到尾下标
前一个字符,示例如下:
1 2 3 4 5
| test = 'name' c1 = test[0:-1] c2 = test[0:3] c3 = test[0:] c4 = test[:3]
|
忽略转义字符
此用法最适合对windows
的路径做处理,路径格式一般为C:\user\file.txt
,在代码中需要对转义字符\
做处理,操作起来比较繁琐。
1 2 3 4
| path = "C:\\user\\file.txt" path2 = r"C:\user\file.txt" test = r"this is a line with \n"
|
字符串拼接
python提供多种拼接方式,常见如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| s1 = 'my' s2 = 'name'
s3 = "this is " + s1 + " " + s2
s3 = 'this is {} {}'.format(s1, s2) s3 = 'this is {1} {0}'.format(s2, s1)
s3 = f'this is {s1} {s2}'
n1 = 30.56 s3 = f'{n1:.1f}摄氏度'
|
打印
1 2 3
| test = 'name' print(test) print(test, end='')
|
格式化
1 2 3 4 5 6 7 8 9 10 11
| s = 'hello, world'
print(s.center(20, '*'))
print(s.rjust(20))
print(s.ljust(20, '~'))
print('33'.zfill(5)) print('-33'.zfill(5))
|