0
text = "hi, hello! hello! I have a cat hello! the fire burns 88988° the planes are sooo fast" #Exmple string

print(len(text))

if(len(text) > 20):
    #text = text[:-10]
    t_len = len(text) +(-len(text) - 10)
    text = text[:-t_len]

print(len(text))
print(text)

I was trying with several things but what I need is that if len (string)> n then extract me and save the last 50 characters in another variable

  • 3
    `text[-50:]` is the last 50 characters. – Barmar Sep 21 '21 at 20:39
  • What do you mean by "extract me" – Jab Sep 21 '21 at 20:40
  • `text[:-10]` is everthing *except* the last 10 characters. – Barmar Sep 21 '21 at 20:40
  • Does this answer your question? [How do I get a substring of a string in Python?](https://stackoverflow.com/questions/663171/how-do-i-get-a-substring-of-a-string-in-python) – Jab Sep 21 '21 at 20:41
  • I wanted to extract the last 50 characters, which would remove the last 50 characters. Just leave those last 50 characters –  Sep 21 '21 at 20:44
  • In your example code, what do you want it to print? Add the desired output to the question. – Barmar Sep 21 '21 at 20:49
  • @Barmar told you how to do that first thing. And you don't eve have to test; if the string is less than 50 characters, that will return the whole string. – Tim Roberts Sep 21 '21 at 20:49
  • @TimRoberts Except that the test seems to be different from the number he wants to extract. It's the last 50, not the last n. – Barmar Sep 21 '21 at 20:51
  • @Barmar Really thanks for the help –  Sep 21 '21 at 21:16

1 Answers1

0

If I understand correct you need something like this:

def extractor(n, string):
    output = ""
    if len(string) > n:
        newstring = string[-50:]
        output = output + newstring
    return output

If you want to only return something id it has more then n, or you want to return the whole string if len(string) > 51. Then you could add an else statement or change the function, but the thing you are asking is solved in the above function.