문제

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