Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does str.lstrip strip an extra character? [duplicate]

Tags:

>>> path = "/Volumes/Users" >>> path.lstrip('/Volume') 's/Users' >>> path.lstrip('/Volumes') 'Users' >>>  

I expected the output of path.lstrip('/Volumes') to be '/Users'

like image 313
Vijayendra Bapte Avatar asked Nov 06 '09 12:11

Vijayendra Bapte


People also ask

What character will Lstrip remove from the beginning of a string?

To remove only leading whitespace and characters, use . lstrip() . This is helpful when you want to remove whitespace and characters only from the start of the string. An example for this would be removing the www.

What does Lstrip and Rstrip do in Python?

rstrip(): returns a new string with trailing whitespace removed. It's easier to remember as removing white spaces from “right” side of the string. lstrip(): returns a new string with leading whitespace removed, or removing whitespaces from the “left” side of the string.

How do you remove leading characters from a string in Python?

Introduction to Python string strip() method If you omit the chars argument or use None , the chars argument will default to whitespace characters. In other words, the strip() will remove leading and trailing whitespace characters from the str .

What is the method used to return a copy of string with leading characters removed?

The lstrip() method returns a copy of the string with leading characters removed (based on the string argument passed). The lstrip() removes characters from the left based on the argument (a string specifying the set of characters to be removed).


1 Answers

lstrip is character-based, it removes all characters from the left end that are in that string.

To verify this, try this:

"/Volumes/Users".lstrip("semuloV/")  # also returns "Users" 

Since / is part of the string, it is removed.

You need to use slicing instead:

if s.startswith("/Volumes"):     s = s[8:] 

Or, on Python 3.9+ you can use removeprefix:

s = s.removeprefix("/Volumes") 
like image 163
Lasse V. Karlsen Avatar answered Oct 10 '22 02:10

Lasse V. Karlsen