Easiest way to calculate number of character in string
Bengt Richter
bokr at oz.net
Wed Dec 21 10:43:49 EST 2005
On 21 Dec 2005 15:57:35 +0100, Ove Svensson <svensson_ove at hotmail.com> wrote:
>Ove Svensson <svensson_ove at hotmail.com> writes:
>
>> "P. Schmidt-Volkmar" <no_spam at tauth.de> writes:
>>
>> > Hi there,
>> >
>> > I have a string in which I want to calculate how often the character ';'
>> > occurs. If the character does not occur 42 times, the ";" should be added so
>> > the 42 are reached.
>> >
>> > My solution is slow and wrong:
>> > for Position in range (0, len(Zeile)):
>> > if Zeile[Position]==';': AnzahlSemikolon = AnzahlSemikolon +1
>> > if AnzahlSemikolon < 42:
>> > for Zaehler in range(AnzahlSemikolon, 42):
>> > Zeile = Zeile + ';'
>> > Dreckskram = Dreckskram +1
>> >
>> > How can this be achieved easily?
>> >
>> > Thanks,
>> >
>> > Pascal
>> >
>> >
>>
>> What about this:
>>
>> Zaehler += ';'*max(0,42-Zaehler.count(';'))
>>
>
>Sorry, should have been
>
>Zeile += ';'*max(0,42-Zeile.count(';'))
I think You don't need the max
>>> for n in xrange(-3,4): print '%3s: %r'%(n, n*';')
...
-3: ''
-2: ''
-1: ''
0: ''
1: ';'
2: ';;'
3: ';;;'
I.e.,
Zeile += ';'*(42-Zeile.count(';'))
should work, since a string is a sequence type and
http://docs.python.org/lib/typesseq.html
Says
"""
Operation Result Notes
...
s * n , n * s n shallow copies of s concatenated (2)
...
(2)
Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). ...
"""
I guess it might be nice to mention this in help(str) also, to publish a useful fact better.
Maybe under str.__mul__ ?
Regards,
Bengt Richter
More information about the Python-list
mailing list