content
1. Remove spaces from the left of the string
2. Remove spaces from the right of the string
3. Remove spaces from both sides of the string
4. Remove spaces from a string (str.replace)
Second, remove the specified character usage:
1. Remove the specified character from the left side of the string
2. Remove the specified character from the right side of the string
3. Remove the specified characters from both sides of the string
4. Remove the specified characters from the string
1. Remove spaces usage:
str.strip() : strips spaces from both sides of a string
str.lstrip() : removes spaces from the left side of a string
str.rstrip() : removes spaces from the right side of a string
Note: spaces here include '\n', '\r', '\t', ' '
1. Remove spaces from the left of the string
path = ' E:/Practice/Imgs/lena.jpg'
img_path = path.lstrip()
print(img_path)
Output: E:/Practice/Imgs/lena.jpg
2. Remove spaces from the right of the string
path = 'E:/Practice/Imgs/lena.jpg '
img_path = path.rstrip()
print(img_path)
Output: E:/Practice/Imgs/lena.jpg
3. Remove spaces from both sides of the string
path = ' E:/Practice/Imgs/lena.jpg '
img_path = path.strip()
print(img_path)
Output: E:/Practice/Imgs/lena.jpg
4. Remove spaces from a string (str.replace)
path = 'E:/ Practice /Imgs /lena.jpg'
img_path = path.replace(' ', '')
print(img_path)
Output: E:/Practice/Imgs/lena.jpg
Second, remove the specified character usage:
str.strip('kk'): removes the characters specified at both ends of the string
str.lstrip('kk'): removes the characters specified on the left
str.rstrip('kk'): removes the characters specified on the right
1. Remove the specified character from the left side of the string
path = 'hello aaa hello ccc hello'
img_path = path.lstrip('hello')
print(img_path)
输出: aaa hello ccc hello
2. Remove the specified character from the right side of the string
path = 'hello aaa hello ccc hello'
img_path = path.rstrip('hello')
print(img_path)
输出:hello aaa hello ccc
3. Remove the specified characters from both sides of the string
path = 'hello aaa hello ccc hello'
img_path = path.strip('hello')
print(img_path)
Output: aaa hello ccc
4. Remove the specified characters from the string
path = 'hello aaa hello ccc hello'
img_path = path.replace('aaa ','')
print(img_path)
输出: hello hello ccc hello