rrfeva
rrfeva

Reputation: 87

Python3 - Replacing spaces with underscore, but skip first element

I have a file with names with spaces. I am trying to make files for each of the names in the file, only using their last names. Here is an example of the file:

Ernest Hemingway
Mark Twain
Ralph Waldo Emerson 
Edgar Allan Poe
Robert Frost

The files created should be in the format of:

Hemingway.txt
Twain.txt
Waldo_Emerson.txt
Allan_Poe.txt

Where the spaces in the last names are replaced by underscores. I am having trouble with getting rid of the first names when replacing the spaces. This is what I have so far:

file_name=name.replace(" ", "_")

I'm not sure how to somehow ignore the first "element" when it replaces. The other thing I thought about doing is to use split.

Upvotes: 1

Views: 337

Answers (5)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

A one-liner using list comprehension, where we ignore the first word, and join all other words in the string with an underscore

li = [ '_'.join(item.split()[1:])+'.txt'  for item in open('file.txt')]
print(li)

So if the file.txt is

Ernest Hemingway
Mark Twain
Ralph Waldo Emerson 
Edgar Allan Poe
Robert Frost

The output will be

['Hemingway.txt', 'Twain.txt', 'Waldo_Emerson.txt', 'Allan_Poe.txt', 'Frost.txt']

Upvotes: 1

yatu
yatu

Reputation: 88305

Here's one way using split and join along with further slicing to generate a list with the specified output structure:

lines = [line.rstrip('\n') for line in open('my_file.txt')]
['_'.join(i.split()[1:]) + '.txt' for i in lines]

Output

['Hemingway.txt',
 'Twain.txt',
 'Waldo_Emerson.txt',
 'Allan_Poe.txt',
 'Frost.txt']

Upvotes: 1

Adarsh Chavakula
Adarsh Chavakula

Reputation: 1599

This should work

name_list = ["Ernest Hemingway","Ralph Waldo Emerson"]
filenames = []
for name in names:
    filenames += ["_".join(name.split(" ")[1:]) + ".txt"]

Upvotes: 0

RenauV
RenauV

Reputation: 383

You can just mix this replace with a substing:

my_string="Ralph Waldo Emerson"
my_string.split(" ",1)[1].replace(" ", "_")

This should do the trick. I hope it helps. BR

Upvotes: 1

Jan Christoph Terasa
Jan Christoph Terasa

Reputation: 5945

Try this:

def get_last_name(name):
    return "_".join(name.split()[1:])

split() splits the string into tokens (separated at whitespaces), and [1:] selects all but the first element of the split. We then join those elements together with an underscore "_".

Upvotes: 3

Related Questions