【问题标题】:How do I make a string if it is greater than n characters then leave only the last 50 characters? [closed]如果字符串大于 n 个字符,我该如何创建一个字符串,然后只留下最后 50 个字符? [关闭]
【发布时间】:2021-11-15 09:24:40
【问题描述】:
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 个字符保存在另一个变量中

【问题讨论】:

  • text[-50:] 是最后 50 个字符。
  • “提取我”是什么意思
  • text[:-10]除了最后 10 个字符。
  • 这能回答你的问题吗? How do I get a substring of a string in Python?
  • 我想提取最后 50 个字符,这将删除最后 50 个字符。留下最后 50 个字符

标签: python python-3.x string text substring


【解决方案1】:

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

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

如果你只想返回 id 多于 n 的东西,或者你想在 len(string) > 51 的情况下返回整个字符串。那么你可以添加一个 else 语句或更改函数,但你是询问在上面的函数中解决了。

【讨论】:

  • 非常感谢您的帮助
猜你喜欢
  • 2022-11-01
  • 2021-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-09
相关资源
最近更新 更多