Python Forum
Help with extracting characters from string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with extracting characters from string
#2
I separated the task in two subtasks.

First Task: Generator to generate indices
Second Task: Join the text. The indices from the generator are used to get the characters.

def index_gen(end):
    """
    GeneratorFunction for indicies

    The generator yield numbers from 0 to < end.
    Example:
    
    >>> list(index_gen(20))
    [0, 1, 3, 6, 10, 15]
    """
    
    current = 0
    step = 1
    
    while current < end:
        yield current
        current += step
        step += 1


def task(text):
    """
    >>> text = "A clown has a red nose."
    >>> task(text)
    'A lnsee'
    """
    return "".join(text[idx] for idx in index_gen(len(text)))


if __name__ == "__main__":
    # Input string: "A clown has a red nose.".
    # Output string: "A lnsee".
    text = "A clown has a red nose."

    print(text)
    print(task(text))
    
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Help with extracting characters from string - by DeaD_EyE - Feb-19-2024, 11:09 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Replacing a few characters of a specified character but not all of them from a string fatherted99 7 3,383 Aug-13-2020, 09:08 AM
Last Post: fatherted99
  Counting the number of occurrences of characters in a string nsadams87xx 1 2,003 Jun-16-2020, 07:22 PM
Last Post: bowlofred
  testing indivudual string for alternating characters Titus444 3 2,820 Nov-01-2018, 10:28 PM
Last Post: j.crater

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020