Question

I am using Python 3.3.

For example, if I opened a file and read the first line using file.readline(), I will get a string of the first line.

Let's say the first line is: line = file.readline().

line will now be: 'Dumbledore, Albus\n'.

If I used:

a = line.strip().split(',')

I will get: ['Dumbledore', ' Albus']

This is where I'm encountering the problem. I do not want the extra space before the first name 'Albus'.

What (simple) approach can I use to remove this?

The purpose of this entire task is to swap the first and last names (for example, from 'Dumbledore, Albus' to 'Albus, Dumbledore'.

Was it helpful?

Solution

Just use str.strip():

s = 'Dumbledore, Albus'
l = [x.strip() for x in s.split(',')]

OTHER TIPS

When you used the strip() function on your readline() output, you used the correct tool that you want to use, albeit at a wrong place.

>>> ' a '.strip()
'a'

Specifically, in your context, you may want to do something like this

>>> a = ['Dumbledore', ' Albus']
>>> a = [x.strip() for x in a]
>>> a
['Dumbledore', 'Albus']

What you are doing is a very simple list comprehension and assigning the final result to the original array.

It is much easier to use a strip or lstrip

a = ['Dumbledore', ' Albus']
a = [item.strip() for item in a]

Given your last edit

names = []
for line in open(myfile).readlines(): #read and act on each line sequentially
    line_list = line.split(',')     # split each line on the comma
    line_list = [item.strip() for line in line_list] # get rid of spaces and newlines
    line_list.reverse()  # reverse the list
    new_name_order = ','.join(line_list)   # join the items with a comma
    names.append(new_name_order)   # add the name to the list of names

The simplest solution is to just split on ', ' instead of ','. So you do:

a = line.strip().split(', ')

You can try in Python:

input = ['Dumbledore', ' Albus']
output = [re.sub(' *', '', x) for x in input]

For completeness you could also use a regular expression:

import re

line = 'Dumbledore, Albus\n'
reformatted = re.sub('(.*?), (.*)', r'\2, \1', line)
# Albus, Dumbledore

Which could be adapted to be:

rx = re.compile('(.*?), (.*?)\n')
with open('yourfile') as fin:
    lines = [rx.sub('\2, \1', line) for line in fin]

As a one-liner:

', '.join([x.strip() for x in line.split(',')][::-1])

Note: [::-1] reverses a list, i.e:

[1, 2, 3][::-1]
=> [3, 2, 1]

A bit clearer for your situation:

lastname, firstname = [x.strip() for x in line.split(',')]
name = firstname + ', ' + lastname
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top