【问题标题】:How to add first 30 chars of a .txt file to a variable?如何将 .txt 文件的前 30 个字符添加到变量中?
【发布时间】:2019-04-04 11:29:43
【问题描述】:

所以我有这个作业问题:

school_prompt.txt 的前30 个字符作为字符串 分配给变量beginning_chars

在上一个问题中,我设法计算了 txt 文件中的所有字符,但我不知道如何将前 30 个添加到变量中。

fname = "school_prompt.txt"
lines = 0
nwords = 0
beginning_chars = 0 
with open(fname, 'r') as f:
    for line in f:
        if line >= 30:
            words = line.split()
            lines +=1 
            nwords += len(words)
            beginning_chars += len(line)

【问题讨论】:

    标签: python string variables character add


    【解决方案1】:

    就这么简单:

    fname = "school_prompt.txt"
    with open(fname, 'r') as f:
        beginning_chars = f.read(30)
    

    read 方法可以将要读取的字节数作为参数。在大多数编码中,一个字节等于一个字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2023-03-12
      • 2015-11-14
      • 2011-03-16
      • 2017-06-24
      • 2022-01-20
      相关资源
      最近更新 更多