I'm using data from a CSV file in my Python program, and I'm facing a problem when trying to run each separate data piece in my program.
If I have a variable like this, which is simply a list of items from each cell in my CSV column:
name = [(x) for x in column_1]
#[Sarah, Thomas, Howard, Lisa]
I want to use individual elements further from this. If I want to replace a link with each name from my column_1 data, and generate a big list of new links, how would I go about doing this?
print(new_link)
www.Sarah.com
www.Thomas.com
www.Lisa.com
My code looks like this so far, but I'm having trouble replacing the list as simply individual element strings from the list:
link = 'www.hello.com'
new_link = link.replace('hello', [(x) for x in name])
Where am I going wrong? Would appreciate any help - thanks!
CodePudding user response:
You are trying to do one replace call with 3 substitutions. You need
new_links = [link.replace('hello', x) for x in name]
That will produce a list of three names.
CodePudding user response:
name = ['Sarah', 'Thomas', 'Howard', 'Lisa']
link = 'www.hello.com'
new_link = [link.replace('hello', x) for x in name]
print(new_link)
output:
['www.Sarah.com', 'www.Thomas.com', 'www.Howard.com', 'www.Lisa.com']