Python字符串 lstrip() 方法
Python String lstrip()方法返回删除了前导字符的字符串副本(基于传递的字符串参数)。如果没有传递参数,它会删除前导空格。
Syntax:
string.lstrip(characters)
Parameters:
- characters [optional]: A set of characters to remove as leading characters.
Returns:
Returns a copy of the string with leading characters stripped.
示例 1
Python3
# Python3 program to demonstrate the use of
# lstrip() method using default parameter
# string which is to be stripped
string = " geeksforgeeks"
# Removes spaces from left.
print(string.lstrip())
Python3
# Python3 program to demonstrate the use of
# lstrip() method using optional parameters
# string which is to be stripped
string = "++++x...y!!z* geeksforgeeks"
# Removes given set of characters from left.
print(string.lstrip("+.!*xyz"))
Python3
# string which is to be stripped
string = "geeks for geeks"
# Argument doesn't contain leading 'g'
# So, no characters are removed
print(string.lstrip('ge'))
Python3
# Python3 program to demonstrate the use of
# strip() method error
string = " geeks for geeks "
list =[1, 2, 3]
# prints the error message
print(list.lstrip())
输出:
geeksforgeeks
示例 2
Python3
# Python3 program to demonstrate the use of
# lstrip() method using optional parameters
# string which is to be stripped
string = "++++x...y!!z* geeksforgeeks"
# Removes given set of characters from left.
print(string.lstrip("+.!*xyz"))
输出:
geeksforgeeks
示例 3
Python3
# string which is to be stripped
string = "geeks for geeks"
# Argument doesn't contain leading 'g'
# So, no characters are removed
print(string.lstrip('ge'))
输出:
ks for geeks
示例4
当我们尝试剥离除字符串之外的任何内容时会出现运行时错误。
Python3
# Python3 program to demonstrate the use of
# strip() method error
string = " geeks for geeks "
list =[1, 2, 3]
# prints the error message
print(list.lstrip())
输出:
print(list.lstrip())
AttributeError: 'list' object has no attribute 'lstrip'