在python中按长度拆分字符串?

2024-05-16 06:38:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,其中有以下文字。我想用python打开文件,读取每一行,然后编辑文件,使每一行仅包含40个字符。在这一行的末尾,我想要一个“+”号。保存文件。 需要帮助来写这个脚本

file = "Starting today (September 17), a range of iPhones and iPads are set to change, courtesy iOS 12. Apple has started the rollout of the next version of its mobile operating system called iOS 12. Available as a free upgrade, iOS 12 will make your iPhones and iPads faster, more secure and add a slew of new features including Memphis, Siri shortcuts and grouped notifications. Wonder if your iPhone and iPad is compatible with the all-new iOS 12? Here's the complete list of devices compatible with the new Apple OS."


Tags: and文件ofthe编辑applenewyour
2条回答

这是一种方法:

它使用Python's textwrap module将文本“包装”成最多40个字符的行,如果你真的想拆分单词或其他任何东西,它也有这些功能

from textwrap import wrap

# File containing your text.
with open("./Text Document.txt", 'r') as read_file:
  data = read_file.read()

data_list = wrap(data, 40)

# New file created with 40 + "+" per line.
with open("./New Text Document.txt", 'w') as write_file:
  for data in data_list:
    write_file.write(data + "+\n")

这将强制执行严格的40个字符限制:

# File containing your text.
with open("./Text Document.txt", 'r') as read_file:
  data = read_file.read()

data_list = []
b, e = 0, 40
while e < len(data):
  data_list.append(data[b:e])
  b += 40
  e += 40
  if e > len(data):
    data_list.append(data[b:len(data)])


# New file created with 40 + "+" per line.
with open("./New Text Document.txt", 'w') as write_file:
  for data in data_list:
    write_file.write(data + "+\n")

file[:40]会给你前40个字符

也可以查看https://docs.python.org/3.1/library/string.html了解更多信息

相关问题 更多 >