在Python 2.7.2中保存原始字符串时,如果字符串太长,则剪切字符串

在Python 2.7.2中保存原始字符串时,如果字符串太长,则剪切字符串,python,Python,我想能够计算字符串长度,包括单词之间的长度,如果超过100个字符,我就必须剪切它。以下是字符串的示例: 'The string99 blah, 2-blahh,........blahhhhhh' 我不想删掉单词,所以如果100个字符出现在单词中间,我需要在这个词的末尾返回。最后一个空格和逗号必须删除。 原始字符串必须另存为文本文件,文件名必须为剪切字符串 有什么帮助吗?您可以使用该模块: 演示: 我可能误解了你的提问,但我认为你的问题的意思是你想做以下事情: 如果字符串长度超过100个字符,

我想能够计算字符串长度,包括单词之间的长度,如果超过100个字符,我就必须剪切它。以下是字符串的示例:

'The string99 blah, 2-blahh,........blahhhhhh'
我不想删掉单词,所以如果100个字符出现在单词中间,我需要在这个词的末尾返回。最后一个空格和逗号必须删除。 原始字符串必须另存为文本文件,文件名必须为剪切字符串

有什么帮助吗?

您可以使用该模块:

演示:


我可能误解了你的提问,但我认为你的问题的意思是你想做以下事情:

如果字符串长度超过100个字符,请删除最后一个逗号和/或空格。 然后,将字符串截断为100个字符。 如果截断发生在单词的正文中,则进一步截断字符串以删除最后一个单词片段。 最后,创建一个文本文件,将截断的字符串作为其文件名,并将原始字符串写入该文件。 我假设如果您没有剪切字符串,那么您希望将文件命名为与原始字符串相同的名称。。。还有,你只有一个字符串。。。不过你不是很清楚,所以我可能想错了。不管怎样,给你:

the_string = "this is a very long string, here is a very long word, f" + ("o" * 50) + " good bye, string, "
filename_string = the_string
if len(the_string) > 100:  
    # if the 100th character is not a space or a comma
    if the_string[99] != " " and the_string[99] != ",":
        # split the string by words, and rejoin all but the last
        # if it ends with a comma, remove it (it won't end in a space because of split())
        filename_string = " ".join(stripped_string[:99].split()[:-1]).rstrip(",")
    else:
        # just remove the last space (and if there is one, a comma)
        filename_string = stripped_string[:100].rstrip(", ")
with open(filename_string, 'w') as outfile:
    outfile.write(the_string)
在运行时,我得到了一个名为这是一个很长的字符串的文件,这是一个很长的单词,它的内容是这是一个很长的字符串,这是一个很长的单词,再见,字符串,。结尾有一个空格,但没有显示出来。正如你所看到的,我没有在Foooooo等中间剪掉,文件名没有用逗号或空格结尾。


如果要对任何旧字符串执行此操作,那么请更改\u字符串。。。或者您可以使用原始输入获取用户输入。。。或者可以使用argparse模块获取命令行参数。你做这项研究是为了弄清楚如何做。

请告诉我们你做了哪些尝试。我们是来帮你解决你没有为你做的事情的。我是个业余爱好者。我已经长大了,对完美地学习Python不感兴趣。我对解决一个具体问题感兴趣。我已经开始使用Python一周了。不幸的是,这对我来说根本不是一种直观的语言。另一方面,这里有许多年轻人渴望磨练Python技能。那么,为我解决一个具体的小问题有什么不对呢?@Ash当你将鼠标悬停在Stack Overflow上的downvote按钮上时,你会看到以下文字:这个问题没有显示任何研究工作;这是不清楚或没有用处。如果你不先尝试自己解决问题,你1学不到任何东西,2会被否决你的问题。谢谢我不知道:非常感谢你的详细回答和解释。我还没有试过,但即使是小问题,我也可以自己解决。
the_string = "this is a very long string, here is a very long word, f" + ("o" * 50) + " good bye, string, "
filename_string = the_string
if len(the_string) > 100:  
    # if the 100th character is not a space or a comma
    if the_string[99] != " " and the_string[99] != ",":
        # split the string by words, and rejoin all but the last
        # if it ends with a comma, remove it (it won't end in a space because of split())
        filename_string = " ".join(stripped_string[:99].split()[:-1]).rstrip(",")
    else:
        # just remove the last space (and if there is one, a comma)
        filename_string = stripped_string[:100].rstrip(", ")
with open(filename_string, 'w') as outfile:
    outfile.write(the_string)