1

I have string like: st= 'Product=Product Name 25' Want to lstrip. output desired: out= 'Product Name 25'

For this i am doing like out = st.lstrip('Product=')

Here I am getting as output as out= 'Name 25'.This is I don't want. As it is removing all occurence in my string but need to remove the first occurence.

Desired output should be: out= 'Product Name 25'

2
  • 2
    That's because lstrip accepts a set of characters to remove, not a string pattern to remove. Commented Jul 14, 2016 at 9:05
  • You say you want to remove the first occurence. That means the string Product= can occur anywhere in the string, not only at the start? Commented Jul 14, 2016 at 9:07

5 Answers 5

4

Use split instead:

>>> st= 'Product=Product Name 25'
>>> st.split("Product=")[1]
'Product Name 25'
Sign up to request clarification or add additional context in comments.

Comments

3

Use replace instead:

st = 'Product=Product Name 25'
print(st.replace('Product=', ''))
>> Product Name 25

If it wasn't for the '=' you could have also take advantage of the count argument that replace has, for example:

st = 'Product Product Name 25'
print(st.replace('Product', '', 1))
>> Product Name 25

Comments

0

You could do out = st.replace('Product=Product','Product') or out = st.replace('Product=Product',''). I tend to find that simple and readable.

Comments

0

Just in case you're reading key-value pairs from a text file, there's a python module in the standard library for that: ConfigParser

Comments

0

According to the documentation, the lstrip function remove the characters in chars.

>>> help(str.lstrip)

Help on method_descriptor:

lstrip(...)
    S.lstrip([chars]) -> str

    Return a copy of the string S with leading whitespace removed.
    **If chars is given and not None, remove characters in chars instead.**

So st.lstrip('Product=') removes "P", "r", "o", "d", "u", "c", "t", "=" at the beginning of "Product=Product Name 25". Then, the two words are removed!

I think your string represents a "key=value" pair. The best way to split it is to use split() method:

st = "Product=Product Name 25"

key, value = st.split("=")
print("key: " + key)
print("value: " + value)

You get:

key: Product
value: Product Name 25

Only the value:

value = st.split("=")[1]
print("value only: " + value)

You get:

value only: Product Name 25

If you want a "left-trim":

p = "Product="
value = st[len(p):]
print("trimmed value: " + value)

You get:

trimmed value: Product Name 25

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.