List output formatting in a variable - python-2.7

I made a Email Bot that crawls Craigslist and emails me when an item meets my queries. I am at the final stage and have everything working but my email format.
What I have is a loop that appends Craigslist Listings to a list. Outside my loop I add the List to my email Def as an argument.
Example of what I need:
list = ['item1', 'item2', 'item3']
print list
['item1', 'item2', 'item3'] # I don't want it on a single line
for i in list:
print i
item1
item2
item3
#I want a variable with the single line item format.
I want the single line format placed into a Variable rather than as the list. My list could be 1 item or 20, depends on what has been posted on Craigslist.
Any help would be great.

With str.join you can join a list by the string given:
"\n".join(my_list)
If you need more fancy formatting than a string per line you should look at a combination of join and str.format
P.S.: By the way, don't shadow the "list" builtin, that's bad practice. It will lead to errors whenever you want to use the builtin.

Not entirely clear what you are asking. As I understand the question, you want to print the list items on different lines, but in the same style as used when printing the list in one line.
The __str__ method of a container class usually uses the __repr__ method of the contained objects, so if you want to print the items on several lines in the same style as when you print it in one line, use the repr function to get the result of __repr__.
>>> lst = ['item1', 'item2', 'item3']
>>> for i in lst:
... print repr(i)
...
'item1'
'item2'
'item3'

Related

how to create a list of a list in photon and print it as columns?

I am new to photon and I would like to know how I can create a list of elements in a list in order to print them on the terminal manually with a number in front of it.
lst = ["country", "inhabitants", "CO2-Emissions" ]
def make_header(lst):
first_column = []
for column_names in range(len(lst)):
first_column.append([])
for list in range(1):
column_names[first_column].append(list)
print(lst)
make_header(lst)
the output should be:
country
inhabitants
Co2 Emissions
Sadly I have no clue how to do that correctly. Could you give me a hint on that?
I want the columns displayed on the terminal as above.
I am not allowed to use maps, arrays, imports and other "fancy" and practical stuff so I approached for a nested loop.
Kind regards
Boris

how to get rid of the space between first and second element? and how to create a "if" statement for selecting information?

19.7435
,5281813.4260,536064.1543,0.371886,out04-36-48-12.tif
lines = f.readlines()
for items in lines:
items = items.replace("\n", "")
#print items
new_file = items.split(",")
new_list_project = ','.join(new_file)
new_list_project = new_list_project.rstrip()
print new_list_project
it always looks like this, but i already used rstrip to remove \n.
19.7435
,5281813.4260,536064.1543,0.371886,out04-36-48-12.tif
also i wanted to select the last element based upon the value of third (0.371886). i write statement but none of them working.
This list has 2000 elements. I might be use for and if statement i guess.
I guess you just have to remove \n after the words. The following code should do it.
f = open("sample.txt")
lines = f.readlines()
for items in lines:
items = [item.strip() for item in items.split(",")]
if items[3] == "0.371886":
print ",".join(items)
else:
print "Whatever you want"
Assuming your file content is:
Elevation, Easting, Northing, Blur metric, Imagery
19.8091 ,5281850.4252,536047.6051,0.335554,out04-32-44-03.tif
19.7435 ,5281813.4260,536064.1543,0.371886,out04-36-48-12.tif
19.8256 ,5281850.5974,536047.2831,0.337232,out04-32-44-15.tif
19.8420 ,5281850.7696,536046.9611,0.4184,out04-32-44-27.tif
19.8584 ,5281850.9418,536046.6392,0.311989,out04-32-44-39.tif
Output:
Whatever you want
Whatever you want
19.7435,5281813.4260,536064.1543,0.371886,out04-36-48-12.tif
Whatever you want
Whatever you want
Whatever you want
If you want to remove the space between first and second element
Try this :
with open("file.txt") as f:
print("".join([i.replace(' ','') for i in f]))
I assumed your data is in a file called "file.txt" .

String from CSV to list - Python

I don't get it. I have a CSV data with the following content:
wurst;ball;hoden;sack
1;2;3;4
4;3;2;1
I want to iterate over the CSV data and put the heads in one list and the content in another list. Heres my code so far:
data = [ i.strip() for i in open('test.csv', 'r').readlines() ]
for i_c, i in enumerate(data):
if i_c == 0:
heads = i
else:
content = i
heads.split(";")
content.split(";")
print heads
That always returns the following string, not a valid list.
wurst;ball;hoden;sack
Why does split not work on this string?
Greetings and merry Christmas,
Jan
The split method returns the list, it does not modify the object in place. Try:
heads = heads.split(";")
content = content.split(";")
I've noticed also that your data seems to all be integers. You might consider instead the following for content:
content = [int(i) for i in content.split(";")]
The reason is that split returns a list of strings, and it seems like you might need to deal with them as numbers in your code later on. Of course, disregard if you are expecting non-numeric data to show up at some point.

Python 2.7 - Iterating Over Elements in 2 Different Lists, Why Each One Print Different Format

In my newbie experimenting and trying to write lots of little scripts and learn; I bumped into this puzzlement:
import re
nouns = ['bacon', 'cheese', 'eggs', 'milk']
article = []
def list_in_list(list1, list2):
for list_1_element in list1:
print list_1_element
for list_2_element in list2:
print list_2_element
with open('test_sentence.txt', 'r') as input_f:
for line in input_f:
article.append(re.findall(r"[\w']+|[.,!?;:]", line))
list_in_list(article, nouns)
Here is the contents of the test_sentence.txt:
I need to go shopping today and some of the things I need to buy are bacon, cheese and eggs. I also need to buy something with a comma in it, such as milk, cheese, and bacon.
What I don't understand is why print list_1_element actually prints the whole 'list1' list such as ['I', 'need', 'to', 'go'.............]. And the the print list_2_element actually prints each element of that list on a new line, as I would expect.
So why the difference?
article.append([some list]) appends the list as one item
article.extend([some list]) would append each item in some list to the article list
Because article is a list containing a single item. You add one list of lists per line, and you have one line.

filter output of subprocess.check_output

I'm trying to match values of a list to a regex pattern. If the particular value within the list matches, I'll append it to a different list of dicts. If the above mentioned value does not match, I want to remove the value from the list.
import subprocess
def list_installed():
rawlist = subprocess.check_output(['yum', 'list', 'installed']).splitlines()
#print rawlist
for each_item in rawlist:
if "[\w86]" or \
"noarch" in each_item:
print each_item #additional stuff here to append list of dicts
#i haven't done the appending part yet
#the list of dict's will be returned at end of this funct
else:
remove(each_item)
list_installed()
The end goal is to eventually be able to do something similar to:
nifty_module.tellme(installed_packages[3]['version'])
nifty_module.dosomething(installed_packages[6])
Note to gnu/linux users going wtf:
This will eventually grow into a larger sysadmin frontend.
Despite the lack of an actual question in your post, I'll make a couple of comments.
You have a problem here:
if "[\w86]" or "noarch" in each_item:
It's not interpreted the way you think of it and it always evaluates to True. You probably need
if "[\w86]" in each_item or "noarch" in each_item:
Also, I'm not sure what you are doing, but in case you expect that Python will do regex matching here: it won't. If you need that, look at re module.
remove(each_item)
I don't know how it's implemented, but it probably won't work if you expect it to remove the element from rawlist: remove won't be able to actually access the list defined inside list_installed. I'd advise to use rawlist.remove(each_item) instead, but not in this case, because you are iterating over rawlist. You need to re-think the procedure a little (create another list and append needed elements to it instead of removing, for example).