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'

Sandy
  • 261
  • 1
  • 3
  • 13
  • 2
    That's because [`lstrip`](https://docs.python.org/3/library/stdtypes.html#str.lstrip) accepts a set of characters to remove, not a string pattern to remove. – Ilja Everilä Jul 14 '16 at 09: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? – Aran-Fey Jul 14 '16 at 09:07

5 Answers5

4

Use split instead:

>>> st= 'Product=Product Name 25'
>>> st.split("Product=")[1]
'Product Name 25'
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
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
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

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

Nolan Zandi
  • 111
  • 9
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

Felix
  • 6,131
  • 4
  • 24
  • 44
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
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103