如果字符串大于 n 个字符然后只保留最后 50 个字符,如何制作一个字符串?

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

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)

我尝试了几件事,但我需要的是如果 len (string)> n 然后提取我并将最后 50 个字符保存在另一个变量中

如果我理解正确,你需要这样的东西:

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

如果你只想 return 某个 id 大于 n 的东西,或者你想 return 整个字符串,如果 len(string) > 51。那么你可以添加一个 else 语句或者改函数,不过你问的问题在上面的函数中已经解决了。