Michael Cividanes
Michael Cividanes

Reputation: 109

stripping out white space and new line characters from a list entry in python

Okay, so I'm working on a program that will do a series of things. First it will read the contents of 2 external files, then it will take each line of said files and convert those lines into a list, and those 2 lists will be combined into one list.

each file is a list of names with an entry number before it, and a new line after it. So each file is a list of between 100 and 200 entries formatted like so:

1.  Michael \n
2.  Ben \n
3.  Ken \n
4.  David \n

so the program opens the file, then reads each line into a list.

Now here is where my problem is arising. I need to strip out the entry number, the white space and the new line command from each line.

I'm using aline.aplit(' ') for each line so that:

1.  Michael \n

would become: ['1. ','Michael \n']

Okay, so from here I should just need to strip off the '\n' and then append[1] to the list of names from this file.

Well this is where I'm getting an error. Specifically:

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'

Here is the full code:

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.")

Upvotes: 0

Views: 709

Answers (2)

MaximTitarenko
MaximTitarenko

Reputation: 886

Use strip() method to get rid of the newline char before splitting.

For example, here is the method to extract the 'name'-part from the following string:

s = '1.  Michael \n'

name = s.strip().split()[1]
print(repr(name)) # 'Michael' => no extra spaces

Let's say, I have the 'names.txt' file with the content:

1.  Michael 
2.  Ben 
3.  Ken 
4.  David 

Then I can get the names from the file in this way:

with open('names.txt') as f:
    names = []
    for line in f.readlines():
        line_elements = line.strip().split()
        if len(line_elements) > 1: # checking for a line in different format 
            name = line_elements[1]
        names.append(name)

print(names) # ['Michael', 'Ben', 'Ken', 'David']

Note that it's preferable to work with files via with open() pattern.

Upvotes: 1

Mahesh Karia
Mahesh Karia

Reputation: 2055

value_xy = aline.split(' ')

above code returns list

entry1 = value_xy.rstrip('\n')

rstrip()/strip() is applicable for strings so this is causing error in both for loops

so you can iterate and append like following example

entry1 = []
for item in value_xy:
    entry1.append(item.rstrip('\n'))

I hope it works

Upvotes: 1

Related Questions