Home > Software design >  select each letter in order from text
select each letter in order from text

Time:08-29

again I would like to help, specifically how I could do it

in order for the script to work like this, I have this script (the function of the script is to select letters from words in order (for example, every second)

for the script below if I print(GetNthLetters("TSASS",2))

so the result is TAS

but I'm looking for the script so that the result is TAS and then continue and add the rest of the letters according to the same principle

so TAS and would continue from the beginning TAS would add SS so the result would be TASSS

could someone help me with this? Thank you

here is mi script

def GetEveryLetters(text, n):
    builtstring = ""
    for index, letter in enumerate(text):
        if index % n == 0:
            builtstring = builtstring   letter
    return builtstring
print(GetEveryLetters("TSASS",2))

here are a few examples of how I want it to outputs

print(GetEveryLetters("TSASS",2))
    TASSS

print(GetNthLetters("TESTTHISIS",3))

TTISEHSITS

I would mainly need support there to select more letters than the number of letters, and I don't know how to do that anymore

ABS every 2 == ASB

thank you very much for your help, I tried to play with it for a long time but it didn't work I came here new to python :D

CodePudding user response:

Slicing makes this trivial:

def get_nth_letters(s, n):
  return s[::n]

Since this doesn't solve all of your problem, you need to repeat this process, n times and join those strings. If n is greater than or equal to len(s), this will return a different string than s. Otherwise it will just return the same value as s.

def get_nth_letters(s, n):
  return ''.join(s[i::n] for i in range(n))

If we run get_nth_letters('helloworld', 3), the first slice generates 'hlwl', the second slice generates eor, and the third slice generates lod. These are then joined to form hlwleorlod.

  • Related