Deutsch English Français Italiano |
<uppercase-20240529190808@ram.dialup.fu-berlin.de> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!fu-berlin.de!uni-berlin.de!not-for-mail From: ram@zedat.fu-berlin.de (Stefan Ram) Newsgroups: comp.lang.python Subject: Re: Flubbed it in the second interation through the string: range error... HOW? Date: 29 May 2024 18:09:07 GMT Organization: Stefan Ram Lines: 40 Expires: 1 Feb 2025 11:59:58 GMT Message-ID: <uppercase-20240529190808@ram.dialup.fu-berlin.de> References: <1064052561.5558929.1716987352732.ref@mail.yahoo.com> <1064052561.5558929.1716987352732@mail.yahoo.com> <407cdc1c-f579-452f-afca-5af50f14d2cb@tompassin.net> <4dddd92a-e0ce-44b7-b376-2de9ee6026a3@mrabarnett.plus.com> <mailman.66.1716994794.2909.python-list@python.org> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Trace: news.uni-berlin.de P1dU5sQJzG2H62QFtqCfMAAvhX3OA7evd4GgAPlOMLZz6c Cancel-Lock: sha1:SbanTd03pJkfBwzzQ+VGMQuSdkY= sha256:paeQo6/RsJ1NWdgVpDwlW+FUJrzIftuIWro3tSDnfhU= X-Copyright: (C) Copyright 2024 Stefan Ram. All rights reserved. Distribution through any means other than regular usenet channels is forbidden. It is forbidden to publish this article in the Web, to change URIs of this article into links, and to transfer the body without this notice, but quotations of parts in other Usenet posts are allowed. X-No-Archive: Yes Archive: no X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some services to mirror the article in the web. But the article may be kept on a Usenet archive server with only NNTP access. X-No-Html: yes Content-Language: en-US Bytes: 2705 MRAB <python@mrabarnett.plus.com> wrote or quoted: >Small mistake there. The original code converted to uppercase on even >indexes, whereas your code does it on odd ones. Here follows my humble effort. import doctest def alternate_uppercase( s ): """ Alternates the case of alphabetic characters in a given string. Args: s (str): The input string. Returns: str: The string with alternating uppercase and lowercase letters. Examples: >>> alternate_uppercase( 'Python is awesome!' ) 'PyThOn Is AwEsOmE!' >>> alternate_uppercase( 'ab,c,,d,,,e,,,,f' ) 'Ab,C,,d,,,E,,,,f' >>> alternate_uppercase( '' ) '' """ result =[ None ]* len( s ) letter_count = 0 for char_pos, char in enumerate( s ): if char.isalpha(): result[ char_pos ]=\ ( char.lower if letter_count%2 else char.upper )() letter_count += 1 else: result[ char_pos ]= char return ''.join( result ) doctest.testmod()