1

I have a string s, and I want to remove '.mainlog' from it. I tried:

>>> s = 'ntm_MonMar26_16_59_41_2018.mainlog'
>>> s.strip('.mainlog')
'tm_MonMar26_16_59_41_2018'

Why did the n get removed from 'ntm...'?

Similarly, I had another issue:

>>> s = 'MonMar26_16_59_41_2018_rerun.mainlog'
>>> s.strip('.mainlog')
'MonMar26_16_59_41_2018_reru'

Why does python insist on removing n's from my strings? How I can properly remove .mainlog from my strings?

Drise
  • 4,310
  • 5
  • 41
  • 66

4 Answers4

2

From Python documentation:

https://docs.python.org/2/library/string.html#string.strip

Currently, it tries to strip all the characters which you mentioned ('.', 'm', 'a', 'i'...)

You can use string.replace instead.

s.replace('.mainlog', '')
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
Sagar Waghmode
  • 767
  • 5
  • 16
2

If you read the docs for str.strip you will see that:

The chars argument is a string specifying the set of characters to be removed.

So all the characters in '.mainlog' (['.', 'm', 'a', 'i', 'n', 'l', 'o', 'g']) are stripped just from the beginning and end.


What you want is str.replace to replace all occurrences of '.mainlog' with nothing:

s.replace('.mainlog', '')
#'ntm_MonMar26_16_59_41_2018'
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
1

You are using the wrong function. strip removes characters from the beginning and end of the string. By default spaces, but you can give a list of characters to remove.

You should use instead:

s.replace('.mainlog', '')

Or:

import os.path
os.path.splitext(s)[0]
Dric512
  • 3,525
  • 1
  • 20
  • 27
1

The argument to the strip function, in this case, .mainlog is not a string, it's a set of individual characters.

That's removing all leading and trailing characters that are in that list.

We'd get the same result if we passed in the argument aiglmno..

spencer7593
  • 106,611
  • 15
  • 112
  • 140