Python 的 lstrip 方法可用于移除字符串左侧的指定字符。默认情况下,它会删除空格并返回一个新字符串。lstrip 函数的语法是:
String_Value.lstrip(Chars)
- Chars: 此参数是可选的,省略此参数表示将空格视为默认参数。要更改默认的空格,请指定要从左侧移除的字符。
Python 字符串 lstrip 方法示例
以下示例集有助于了解 lstrip 函数。
Str1 = ' Tutorial Gateway'
Str2 = Str1.lstrip()
print('Stripping Whitespaces on Left is =', Str2)
# Observe the Original String
print('Converted String is =', Str1.lstrip())
print('Original String is =', Str1)
# Performing directly
Str3 = '00000000Tutorial Gateway00000000'.lstrip('0')
print("Stripping 0's on Left is =", Str3)
# Stripping Left Side
Str4 = '+++++*********Tutorial Gateway'.lstrip('+*')
print('Stripping + and * on Left is =', Str4)

此函数用于移除字符串变量 Str1 左侧的空空格,并打印输出。
Str2 = Str1.lstrip()
print('Stripping Whitespaces on Left using LStrip() is =', Str2)
默认情况下,lstrip 函数以新字符串的形式返回输出。
print('Converted String is =', Str1.lstrip())
print('Original String is =', Str1)
要修改原始内容,请编写以下语句。
Str1 = Str1.lstrip()
lstrip 函数仅移除字符串左侧的指定字符,而忽略右侧的所有字符。
在接下来的 字符串函数 语句中,我们两侧都有零。此外,请参见上图,输出仅从左侧移除了零。
Str3 = '00000000Tutorial Gateway00000000'.lstrip('0')
print("Stripping 0's on Left using LStrip() is =", Str3)
在此 Python 语句中,我们使用了两个字符(+ 和 *)从左侧进行移除。
Str4 = '+++++*********Tutorial Gateway'.lstrip('+*')
print('Stripping + and * on Left using LStrip() is =', Str4)