lstrip()方法返回已除去前導字符的字符串的副本(基於傳遞的字符串參數)。如果未傳遞任何參數,它將刪除前導空格。
用法: string.lstrip(characters)
參數:
characters[可選]:一組要刪除的前導字符。
返回:返回去除前導字符的字符串副本。
代碼1:
# 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())
輸出:
geeksforgeeks
代碼2:
# 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:
# 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 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'
相關用法
- Numpy string lstrip()用法及代碼示例
- Python string islower()用法及代碼示例
- Python string isupper()用法及代碼示例
- Python string capwords()用法及代碼示例
注:本文由純淨天空篩選整理自AKASH GUPTA 6大神的英文原創作品 Python String | lstrip() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。