سؤال

I don't really understand the .strip function.

Say I have a string

xxx = 'hello, world'

and I want to strip the comma. Why doesn't

print xxx.strip(',')

work?

هل كانت مفيدة؟

المحلول

str.strip() removes characters from the start and end of a string only. From the str.strip() documentation:

Return a copy of the string with the leading and trailing characters removed.

Emphasis mine.

Use str.replace() to remove text from everywhere in the string:

xxx.replace(',', '')

For a set of characters use a regular expression:

import re

re.sub(r'[,!?]', '', xxx)

Demo:

>>> xxx = 'hello, world'
>>> xxx.replace(',', '')
'hello world'

نصائح أخرى

str.strip removes characters from the beginning or end of the string, not in the middle.

>>> ',hello, world,'.strip(',')
'hello, world'

If you want remove character from everywhere, you should use str.replace instead:

>>> 'hello, world'.replace(',', '')
'hello world'

You can also use the translate method of the string class. If you pass in None for the table parameter, then only the character deletion step is executed.

>>> 'hello, world'.translate(None,',')
'hello world'
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top