Home > Software engineering >  How do I make a string if it is greater than n characters then leave only the last 50 characters?
How do I make a string if it is greater than n characters then leave only the last 50 characters?

Time:09-22

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

CodePudding user response:

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.

  • Related