python 去除空格和换行,在python中从列表项中去掉空格和换行符

好吧,我正在做一个程序,它可以做一系列的事情。它首先读取2个外部文件的内容,然后将所述文件的每一行转换成一个列表,然后将这两个列表合并成一个列表。在

每个文件都是一个名称列表,前面有一个条目号,后面有一个新行。因此,每个文件都是100到200个条目的列表,格式如下:1. Michael \n

2. Ben \n

3. Ken \n

4. David \n

所以程序打开文件,然后把每一行读到一个列表中。在

这就是我的问题所在。我需要从每一行中去掉条目号、空白和换行命令。在

我在用阿琳·阿普利特('')对于每一行,以便:

^{pr2}$

会变成:

['1','Michael\n']

好的,从这里开始,我只需要去掉'\n',然后将[1]附加到这个文件的名称列表中。在

好吧,这就是我出错的地方。具体来说:Traceback (most recent call last):

File "H:/ITP100/assignments/Chapter 7/Names-3.py", line 30, in

entry1 = value_xy.rstrip('\n')

AttributeError: 'list' object has no attribute 'rstrip'

以下是完整代码:Name1 = (input("Enter a name: "))

file_xy = open("BoyNames.txt", "r")

list_xy = []

file_xx = open("GirlNames.txt", "r")

list_xx = []

test_boys =[]

test_girls =[]

entry1 = []

for aline in file_xy:

value_xy = aline.split(' ')

entry1 = value_xy.rstrip('\n')

test_boys.append[1]

#entry2 = entry1[1].strip()

list_xy.append(entry1[1])

for aline in file_xx:

value_xx = aline.split(' ')

entry_xx1 = value_xx.rstrip('\n')

test_girls.append(entry_xx1)

# entry_xx2 = value_xx[1].lstrip()

list_xx.append(entry_xx1)

#print(list_xy)

names = list_xy + list_xx

print("This is the list \'names\'. This is the combined list of all names."+'\n'+str(names))

print("This is the list \'test_boys\'. This is the post-stripping list of boy names."+'\n'+str(test_boys))

print("This is the list \'test_girls\'. This is the post-stripping list of girl names."+'\n'+str(test_girls))

if Name1 in names:

print(Name1+" is in the list.")

else:

print(Name1+" is not in the list.")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值