How to not convert string into a list? - python

I am making an item menu in console app whereby i get the data from a text file and print it as shown in the code snippet below.
with open("itemList.txt", "r") as itemFile:
for row in itemFile:
row = row.strip("\n")
itemlist.append(row.split())
print("\n---------------------")
print("Welcome!"+userName)
print("---------------------\n")
for everything in itemlist:
itemCode = everything[0]
itemName = str(everything[1]).split("_")
itemPrice = everything[2]
itemQuantity = everything[3]
print(itemCode+"\t|"+itemName+"\t|"+itemPrice+"\t|"+itemQuantity+"\n")
My problem here is that, in my data there are names like "Full_Cream_Milk" which will be joined together with a "_" so i am using .split() to try to remove it and change print it as "Full Cream Milk", but in doing so it will change my itemName variables into a list which causes the error:
Exception has occurred: TypeError
can only concatenate str (not "list") to str
my question now is that, how do i not make my itemName into a list? Or are there any better ways to remove the "_"?
I have also tried writing it as shown below and it still changes it into string and I'm not sure is it because im getting the data from a list or what because it worked before adding the split() function
itemName = everything[1]
itemName = itemName.split("_")

My guess is you want to split 'Full_Cream_Milk' by '_' and later join the split part as 'FullCreamMilk'. In that case, the following snippet will do the work.
itemName = everything[1]
split_words = itemName.split("_")
itemName = ''.join(split_words)

If you wish to remove all of the underscores, you can use re.sub.
import re
itemName = re.sub('_', '', everything[1])
Or just str.replace.
itemName = everything[1].replace('_', '')

Related

How can I replace an item in a list with a string that has a space in it?

I am trying to simply replace a list item with another item, except the new item has a space in it. When it replaces, it creates two list items when I only want one. How can I make it just one item in the list please?
Here is a minimal reproducible example:
import re
cont = "BECMG 2622/2700 32010KT CAVOK"
actual = "BECMG 2622"
sorted_fm_becmg = ['BECMG 262200', '272100']
line_to_print = 'BECMG 262200'
becmg = re.search(r'%s[/]\d\d\d\d' % re.escape(actual), cont).group()
new_becmg = "BECMG " + becmg[-4:] + "00" # i need to make this one list item when it replaces 'line_to_print'
sorted_fm_becmg = (' '.join(sorted_fm_becmg).replace(line_to_print, new_becmg)).split()
print(sorted_fm_becmg)
I need sorted_fm_becmg to look like this : ['BECMG 270000', '272100'].
I've tried making new_becmg a list item, I have tried removing the space in the string in new_becmg but I need the list item to have a space in it.
It is probably something simple but I can't get it. Thank you.
You can iterate through sorted_fm_becmg to replace each string individually instead:
sorted_fm_becmg = [b.replace(line_to_print, new_becmg) for b in sorted_fm_becmg]

Why Does This Return None when entering a list[0]?

'zipcodes.txt' is a text file with just zipcodes. The script works correct if I just enter a zipcode e.g. "90210". zip_list[0] type is a string and when printed it returns a single zipcode. However with the code as is a keep getting 'None'
from uszipcode import SearchEngine
search = SearchEngine(simple_zipcode=False)
zip_list = list(open("zipcodes.txt","r"))
search_by_zip = search.by_zipcode(zip_list[0])
print(search_by_zip.major_city)
I changed the variable names around a bit to make sense for me, but I had to strip() the list to get rid of the '\n'
first_list = list(open("zipcodes.txt","r"))
zip_list = []
for item in first_list:
zip_list.append(item.strip())

Is there a way to combine bold text from Markdown and a list onto one line without the brackets and quotes?

So I'm trying to print some bold text and on the same line, I want it to print a list. However, I can't seem to get the list to print without the brackets and quotes on the same line. I can print the bold text and the list with brackets fine but I don't want the brackets and quotes. I am using Markdown to get my bold text
Examples of what I'm getting:
Genres: ['Horror', 'Crime'] or
Horror, Crime
Genres: None
What I want:
Genres: Horror, Crime
from IPython.display import Markdown, display
def getGenre():
genres = []
all_genres = []
genre_names = []
api_key = 'api'
our_movie_genre_ids = movies['results'][overview_length].get('genre_ids')
genre_response = requests.get('https://api.themoviedb.org/3/genre/movie/list?api_key=' + api_key + '&language=en-US')
genre = genre_response.json()
for i in range(0,len(genre['genres'])):
all_genres.append(genre['genres'][i].get('id'))
genre_names.append(genre['genres'][i].get('name'))
for i in range(0,len(our_movie_genre_ids)):
for j in range(0,len(all_genres)):
if our_movie_genre_ids[i] == all_genres[j]:
genres.append(genre_names[j])
return str(genres)
def printbold(string):
display(Markdown(string))
printbold("**Genres:**" + ' ' + getGenre())
It is hard to replicate your issue, considering that you are using api call to get the data. But I am assuming that your issue is in the way you handle your list return. Instead of using
return str(genres)
in your getGenre() function call, you can try
','.join(genres)
to get genres as a string. I hope that helps.

How do I avoid errors when parsing a .csv file in python?

I'm trying to parse a .csv file that contains two columns: Ticker (the company ticker name) and Earnings (the corresponding company's earnings). When I read the file using the following code:
f = open('earnings.csv', 'r')
earnings = f.read()
The result when I run print earnings looks like this (it's a single string):
Ticker;Earnings
AAPL;52131400000
TSLA;-911214000
AMZN;583841600
I use the following code to split the string by the break line character (\n), followed by splitting each resulting line by the semi-colon character:
earnings_list = earnings.split('\n')
string_earnings = []
for string in earnings_list:
colon_list = string.split(';')
string_earnings.append(colon_list)
The result is a list of lists where each list contains the company's ticker at index[0] and its earnigns at index[1], like such:
[['Ticker', 'Earnings\r\r'], ['AAPL', '52131400000\r\r'], ['TSLA', '-911214000\r\r'], ['AMZN', '583841600\r\r']]
Now, I want to convert the earnings at index[1] of each list -which are currently strings- intro integers. So I first remove the first list containing the column names:
headless_earnings = string_earnings[1:]
Afterwards I try to loop over the resulting list to convert the values at index[1] of each list into integers with the following:
numerical = []
for i in headless_earnings:
num = int(i[1])
numerical.append(num)
I get the following error:
num = int(i[1])
IndexError: list index out of range
How is that index out of range?
You certainly mishandle the end of lines.
If I try your code with this string: "Ticker;Earnings\r\r\nAAPL;52131400000\r\r\nTSLA;-911214000\r\r\nAMZN;583841600" it works.
But with this one: "Ticker;Earnings\r\r\nAAPL;52131400000\r\r\nTSLA;-911214000\r\r\nAMZN;583841600\r\r\n" it doesn't.
Explanation: split creates a last list item containing only ['']. So at the end, python tries to access [''][1], hence the error.
So a very simple workaround would be to remove the last '\n' (if you're sure it's a '\n', otherwise you might have surprises).
You could write this:
earnings_list = earnings[:-1].split('\n')
this will fix your error.
If you want to be sure you remove a last '\n', you can write:
earnings_list = earnings[:-1].split('\n') if earnings[-1] == '\n' else earnings.split('\n')
EDIT: test code:
#!/usr/bin/env python2
earnings = "Ticker;Earnings\r\r\nAAPL;52131400000\r\r\nTSLA;-911214000\r\r\nAMZN;583841600\r\r\n"
earnings_list = earnings[:-1].split('\n') if earnings[-1] == '\n' else earnings.split('\n')
string_earnings = []
for string in earnings_list:
colon_list = string.split(';')
string_earnings.append(colon_list)
headless_earnings = string_earnings[1:]
#print(headless_earnings)
numerical = []
for i in headless_earnings:
num = int(i[1])
numerical.append(num)
print numerical
Output:
nico#ometeotl:~/temp$ ./test_script2.py
[52131400000, -911214000, 583841600]

Including Exception in python

I have a file at /location/all-list-info.txt underneath I have some items in below manner:
aaa:xxx:abc.com:1857:xxx1:rel5t2:y
ifa:yyy:xyz.com:1858:yyy1:rel5t2:y
I process these items with a below python code:
def pITEMName():
global itemList
itemList = str(raw_input('Enter pipe separated list of ITEMS : ')).upper().strip()
items = itemList.split("|")
count = len(items)
print 'Total Distint Item Count : ', count
pipelst = itemList.split('|')
filepath = '/location/all-item-info.txt '
f = open(filepath, 'r')
for lns in f:
split_pipe = lns.split(':', 1)
if split_pipe[0] in pipelst:
index = pipelst.index(split_pipe[0])
del pipelst[index]
for lns in pipelst:
print lns,' is wrong item Name'
f.close()
if podList:
After execution of above python code its gives a prompt as :
Enter pipe separated list of ITEMS:
And then I passes the items :
Enter pipe separated list of ITEMS: aaa|ifa-mc|ggg-mc
now after pressing enter above code process further like below :
Enter pipe separated list of ITEMS : aaa|ifa-mc|ggg-mc
Total Distint Item Count : 3
IFA-MC is wrong Item Name
GGG-MC is wrong Item Name
ITEMs Belonging to other Centers :
Item Count From Other Center = 0
ITEMs Belonging to Current Centers :
Active Items in US1 :
^IFA$
Test Active Items in US1 :
^AAA$
Ignored Item Count From Current center = 0
You Have Entered ItemList belonging to this center as: ^IFA$|^AAA$
Active Pod Count : 2
My question is if I suffix the '-mc' in items while giving the input its given me as wrong item whereas it presents in /location/all-item-info.txt file with not present the item in /location/all-item-info.txt . Please have a look at below output again :
IFA-MC is wrong Item Name
GGG-MC is wrong Item Name
In above example 'ifa' is present in /location/all-items-info.txt path whereas as ggg is not present.
Request you to help me here what can I do on above code so if I suffix the -mc which are present in /location/all-items-info.txt file it should not count as wrong item name. it should count only for those items which are not present in /location/all-items-info.txt file.
Please give you help.
Thanks,
Ritesh.
If you want to avoid checking for -mc as well, then you can modify this part of your script -
pipelst = itemList.split('|')
To -
pipelst = [i.split('-')[0] for i in itemList.split('|')]
It's a bit unclear exactly what you are asking, but basically to ignore any '-mc' from user input, you can explicitly preprocess the user input to strip it out:
pipelst = itemList.split('|')
pipelst = [item.rsplit('-mc',1)[0] for item in pipelst]
If instead you want to allow for the possibility of -mc-suffixed words in the file as well, simply add the stripped version to the list instead of replacing
pipelst = itemList.split('|')
for item in pipelist:
if item.endswith('-mc'):
pipelst.append(item.rsplit('-mc',1)[0])
Another issue may be based on the example lines you gave from /location/all-list-info.txt, it sounds like all the items are lowercase. However, pipelst is explicitly making the user input all uppercase. String equality and in mechanics is case-sensitive, so for instance
>>> print 'ifa-mc' in ['IFA-MC']
False
You probably want:
itemList = str(raw_input('Enter pipe separated list of ITEMS : ')).lower().strip()
and you could use .upper() only when printing or wherever it is needed
Finally, there are a few other things that could be tweaked with the code just to make things a bit faster and cleaner. The main one that comes to mind is it seems like pipelst should be a python set and not a list as checking inclusion and removal would then be much faster for large lists, and the code to remove an item from a set is much cleaner:
>>> desserts = set(['ice cream', 'cookies', 'cake'])
>>> if 'cake' in desserts:
... desserts.remove('cake')
>>> print desserts
set(['cookies', 'ice cream'])

Categories