因此,一位朋友认为通过将一长串单个单词放入由换行符分隔的引号中,他们会非常有用。我最终需要这些都是单个字符串放入列表而没有它们的换行符。
新的python所以也许有一些我很想念的东西?
我尝试过使用splitlines(),但它对多行字符串不太好用。当我不使用多行字符串时,我不知道如何将所有单词放在一行上,这就是问题的开始。
food = '''
'apple'
'hot cakes'
'hot dogs'
'pie'
'watermelon'
'''
print(food.splitlines())
上面的代码实际上给了我的是:
['', "'apple'", "'hot cakes'", "'hot dogs'", "'pie'", "'watermelon'"]
但我想给它的是:
['apple', 'hot cakes', 'hot dogs'...]
使用replace
摆脱引号并使用splitlines
并摆脱第一行元素(空字符串):
print(food.replace("'",'').splitlines()[1:])
输出:
['apple', 'hot cakes', 'hot dogs', 'pie', 'watermelon']
你和splitlines()
的关系非常接近。你和splitlines()
有两个主要问题。首先是你得到空字符串,其中一行没有字。第二个是你仍然留下了引号。下面的代码解决了这两个问题:
food_split = [word.replace("'", '') for word in food.splitlines() if word.strip()]
这大致相当于(但快得多):
food_split = []
for word in food.splitlines():
if word.strip(): # check if the word is empty
food_split.append(word.replace("'", '')) # replace quotes with empty string
if word.strip()
确保忽略任何只有空格的空白行,而word.replace("'", '')
用空字符串替换额外的单引号。
你可以使用python列表理解如下:
>>> food = '''
... 'apple'
... 'hot cakes'
... 'hot dogs'
... 'pie'
... 'watermelon'
... '''
>>> [x.replace("'", '') for x in food.splitlines() if x]
['apple', 'hot cakes', 'hot dogs', 'pie', 'watermelon']
简单!
print([x.strip("'") for x in food.splitlines() if x])
在list comprehension中使用strip()