如何有效地使用strip()函数

Rom*_*ker -1 python

你能告诉我为什么strip()函数不起作用吗?

str1= 'aaaadfffdswefoijeowji'

def char_freq():
    for x in range (0, len(str1)):
        sub = str1[x]
        print 'the letter',str1[x],'appearence in the sentence=', str1.count(sub, 0,len(str1))
        str1.strip(str1[x])

def main():
    char_freq()

main()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 7

.strip()工作正常,但字符串是不可变的.str.strip() 返回新的剥离字符串:

>>> str1 = 'foofoof'
>>> str1.strip('f')
'oofoo'
>>> str1
'foofoof'
Run Code Online (Sandbox Code Playgroud)

您忽略了返回值.但是,如果你确实存储了更改的字符串,那么你的for循环将会运行IndexError,因为下一次迭代时字符串会更短:

>>> for x in range (0, len(str1)):
...     str1 = str1.strip(str1[x])
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: string index out of range
Run Code Online (Sandbox Code Playgroud)

要计算字符串,不要str.strip() ; 只是从字符串的开头和结尾删除字符,而不是在中间.你可以使用,str.replace(character, '')但也会效率低下; 但结合一个while循环,以避免IndexError看起来像这样的问题:

while str1:
    c = str1[0]
    print 'the letter {} appearence in the sentence={}'.format(c, str1.count(c))
    str1 = str1.replace(c, '')
Run Code Online (Sandbox Code Playgroud)

更容易使用一个collections.Counter()对象:

from collections import Counter

freq = Counter(str1)
for character, count in freq.most_common():
    print '{} appears {} times'.format(character, count)
Run Code Online (Sandbox Code Playgroud)

如果没有专用Counter对象,您可以使用字典来计算字符:

freq = {}
for c in str1:
    if c not in freq:
        freq[c] = 0
    freq[c] += 1

for character, count in freq.items():
    print '{} appears {} times'.format(character, count)
Run Code Online (Sandbox Code Playgroud)

其中,freq然后在循环后保持字符计数.