对于我的清单:
['ham\tGo until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...\n',
'ham\tOk lar... Joking wif u oni...\n',
"spam\tFree entry in 2 a wkly comp to win FA Cup final tkts 21st May 2005. Text FA to 87121 to receive entry question(std txt rate)T&C's apply 08452810075over18's\n",
'ham\tU dun say so early hor... U c already then say...\n',
"ham\tNah I don't think he goes to usf, he lives around here though\n"]
您可以清楚地看到每行以换行符结尾。我想删除这些换行符,并编写一个函数,该函数在传递给它的任何字符串的末尾删除所有多余的换行符(换行符的数量可能大于或等于0)。
您可以使用.replace。
例如
myString = "test"
newString = myString.replace("e","a")
print(newString)
newString将打印“ tast”,将测试中的e替换为a
您可以对列表执行相同的操作,遍历每个项目
myList = ["test\n","abc\n","python\n"]
for num,item in enumerate(myList):
myList[num] = item.replace("\n","")
print(myList)
尝试一下:
my_list = ['ham\tGo until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...\n',
'ham\tOk lar... Joking wif u oni...\n',
"spam\tFree entry in 2 a wkly comp to win FA Cup final tkts 21st May 2005. Text FA to 87121 to receive entry question(std txt rate)T&C's apply 08452810075over18's\n",
'ham\tU dun say so early hor... U c already then say...\n',
"ham\tNah I don't think he goes to usf, he lives around here though\n"]
for i in range(len(my_list)) :
my_list[i] = my_list[i].replace("\n","")