[英]How to use the strip() function efficiently
Can you please tell me why the strip() function does not work? 您能告诉我为什么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()
.strip()
is working just fine, but strings are immutable. .strip()
工作正常,但是字符串是不可变的。 str.strip()
returns the new stripped string: str.strip()
返回新的剥离字符串:
>>> str1 = 'foofoof'
>>> str1.strip('f')
'oofoo'
>>> str1
'foofoof'
You are ignoring the return value. 您忽略了返回值。 If you do store the altered string, however, your
for
loop will run into an IndexError
, as the string will be shorter the next iteration: 但是,如果您确实存储了更改后的字符串,则您的
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
To count strings, don't str.strip()
; 要计算字符串, 请不要
str.strip()
; that just removes characters from the start and end of a string, not in the middle. 只是从字符串的开头和结尾而不是中间删除字符。 You could use
str.replace(character, '')
but that would be inefficient too; 您可以使用
str.replace(character, '')
但这也效率不高; but combined with a while
loop to avoid the IndexError
problem that'd look like: 但结合使用
while
循环可避免出现类似以下内容的IndexError
问题:
while str1:
c = str1[0]
print 'the letter {} appearence in the sentence={}'.format(c, str1.count(c))
str1 = str1.replace(c, '')
Much easier would be to just use a collections.Counter()
object : 仅使用
collections.Counter()
对象会容易得多 :
from collections import Counter
freq = Counter(str1)
for character, count in freq.most_common():
print '{} appears {} times'.format(character, count)
Without a dedicated Counter
object, you could use a dictionary to count characters instead: 如果没有专用的
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)
where freq
then holds character counts after the loop. 然后
freq
在循环后保存字符计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.