在哪里放str.strip

时间:2013-12-01 18:50:49

标签: python string strip

我为计算机生成的madlibs编写了一个代码:

from random import randrange
print 'Welcome to Madlibs!'
def choose():
    f = open('/usr/share/dict/words')
    content = f.readlines()
    return content[randrange(len (content))]
word = choose()
wordone = choose()
wordtwo = choose()
print 'there was a boy called', word, 'that had a', wordone, 'as a', wordtwo

在变量词之后有一个换行符,因为在文件中它们在每个单词后面都包含换行符。我知道删除换行符的正确命令是str.strip,但我不确定把它放在哪里。

2 个答案:

答案 0 :(得分:0)

当您知道可以从字符串的开头和结尾剪掉字符时,您放置.strip()。在这种情况下,你会在逐行阅读时把它放在一边。

def choose():
    with open('/usr/share/dict/words') as f:
        content = [line.strip() for line in f]

答案 1 :(得分:0)

即使您必须阅读整个文件,您也无需将其读入内存以选择一组随机单词,例如:

import heapq
import random

with open('yourfile') as fin:
    # Make generator that has lines stripped of newlines/whitespace from end of words
    stripped_lines = (line.rstrip() for line in fin)
    # Get three random words by taking one with largest random number
    word1, word2, word3 = heapq.nlargest(3, stripped_lines, key=lambda L: random.random())
    print 'There was a boy called {} that had a {} as a {}'.format(word1, word2, word3)