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
#1
For our project we need to extract single characters from a given string which are separated from each other by the increasing number of places. Each extracted character must be exactly one place more apart from its predecessor than the one before. We need to use a string formed from the extracted characters as an input for the next phase of the project. Does anyone know how to solve this.

Example:
Input string: "A clown has a red nose.".
Output string: "A lnsee".
Reply
#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
#3
Well, DeaD_EyE does it cooler!

Interesting however!

# shortcut to the first 2 places
result = [s[0], s[1]]
diff = 1
for l in range(2, len(s)):
    diff +=l
    if len(s) < diff:
        break
    result.append(s[diff])
    restring = ''.join(result)
    print(restring)
DeaD_EyE likes this post
Reply


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,232 Aug-13-2020, 09:08 AM
Last Post: fatherted99
  Counting the number of occurrences of characters in a string nsadams87xx 1 1,926 Jun-16-2020, 07:22 PM
Last Post: bowlofred
  testing indivudual string for alternating characters Titus444 3 2,667 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