目录
一、去除空格用法:
str.strip() : 去除字符串两边的空格
str.lstrip() : 去除字符串左边的空格
str.rstrip() : 去除字符串右边的空格
注:此处的空格包含'\n', '\r', '\t', ' '
1. 去除字符串左边的空格
path = ' E:/Practice/Imgs/lena.jpg'
img_path = path.lstrip()
print(img_path)
输出:E:/Practice/Imgs/lena.jpg
2. 去除字符串右边的空格
path = 'E:/Practice/Imgs/lena.jpg '
img_path = path.rstrip()
print(img_path)
输出:E:/Practice/Imgs/lena.jpg
3. 去除字符串两边的空格
path = ' E:/Practice/Imgs/lena.jpg '
img_path = path.strip()
print(img_path)
输出:E:/Practice/Imgs/lena.jpg
4. 去除字符串中的空格(str.replace)
path = 'E:/ Practice /Imgs /lena.jpg'
img_path = path.replace(' ', '')
print(img_path)
输出:E:/Practice/Imgs/lena.jpg
二、去除指定字符用法:
str.strip('kk') :去除字符串两端指定的字符
str.lstrip('kk') :用于去除左边指定的字符
str.rstrip('kk') :用于去除右边指定的字符
1. 去除字符串左边的指定字符
path = 'hello aaa hello ccc hello'
img_path = path.lstrip('hello')
print(img_path)
输出: aaa hello ccc hello
2. 去除字符串右边的指定字符
path = 'hello aaa hello ccc hello'
img_path = path.rstrip('hello')
print(img_path)
输出:hello aaa hello ccc
3. 去除字符串两边的指定字符
path = 'hello aaa hello ccc hello'
img_path = path.strip('hello')
print(img_path)
输出: aaa hello ccc
4. 去除字符串中的指定字符
path = 'hello aaa hello ccc hello'
img_path = path.replace('aaa ','')
print(img_path)
输出: hello hello ccc hello