Remove comma and change string to float - python

I want to find "money" in a file and change the string to float , for example, I use regular expression to find "$33,326" and would like to change to [33326.0, "$"] (i.e., remove comma, $ sign and change to float). I wrote the following function but it gives me an error
import locale,re
def currencyToFloat(x):
empty = []
reNum = re.compile(r"""(?P<prefix>\$)?(?P<number>[.,0-9]+)(?P<suffix>\s+[a-zA-Z]+)?""")
new = reNum.findall(x)
for i in new:
i[1].replace(",", "")
float(i[1])
empty.append(i[1])
empty.append(i[0])
return empty
print currencyToFloat("$33,326")
Can you help me debug my code?

money = "$33,326"
money_list = [float("".join(money[1:].split(","))), "$"]
print(money_list)
OUTPUT
[33326.0, '$']

When you do
float(i[1])
you are not modifying anything. You should store the result in some variable, like:
temp = ...
But to cast to float your number have to have a dot, not a comma, so you can do:
temp = i[1].replace(",", ".")
and then cast it to float and append to the list:
empty.append(float(temp))
Note:
Something important you should know is that when you loop through a list, like
for i in new:
i is a copy of each element, so if you modify it, no changes will be done in the list new. To modify the list you can iterate over the indices:
for i in range(len(new)):
new[i] = ...

You can use str.translate()
>>>money= "$333,26"
>>>float(money.translate(None, ",$"))
33326.0

With Python 3 you can use str.maketrans with str.translate:
money = "$33,326"
print('money: {}'.format(float(money.translate(str.maketrans('', '', ",$")))))
Output: money: 33326.0

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]

Remove Prefixes From a String

What's a cute way to do this in python?
Say we have a list of strings:
clean_be
clean_be_al
clean_fish_po
clean_po
and we want the output to be:
be
be_al
fish_po
po
Another approach which will work for all scenarios:
import re
data = ['clean_be',
'clean_be_al',
'clean_fish_po',
'clean_po', 'clean_a', 'clean_clean', 'clean_clean_1']
for item in data:
item = re.sub('^clean_', '', item)
print (item)
Output:
be
be_al
fish_po
po
a
clean
clean_1
Here is a possible solution that works with any prefix:
prefix = 'clean_'
result = [s[len(prefix):] if s.startswith(prefix) else s for s in lst]
You've merely provided minimal information on what you're trying to achieve, but the desired output for the 4 given inputs can be created via the following function:
def func(string):
return "_".join(string.split("_")[1:])
you can do this:
strlist = ['clean_be','clean_be_al','clean_fish_po','clean_po']
def func(myList:list, start:str):
ret = []
for element in myList:
ret.append(element.lstrip(start))
return ret
print(func(strlist, 'clean_'))
I hope, it was useful, Nohab
There are many ways to do based on what you have provided.
Apart from the above answers, you can do in this way too:
string = 'clean_be_al'
string = string.replace('clean_','',1)
This would remove the first occurrence of clean_ in the string.
Also if the first word is guaranteed to be 'clean', then you can try in this way too:
string = 'clean_be_al'
print(string[6:])
You can use lstrip to remove a prefix and rstrip to remove a suffix
line = "clean_be"
print(line.lstrip("clean_"))
Drawback:
lstrip([chars])
The [chars] argument is not a prefix; rather, all combinations of its values are stripped.

regarding list object's attributes

While I am writing this code lst=list(map(int,input().split().strip())) then I am getting an AttributeError 'list' object has no attribute strip
But it is working when I remove the strip() method.
My question is that list object also has no attribute split. So in this case (lst=list(map(int,input().split())) why it is not giving any error and why it is giving error in case of strip() method?
Before you read the rest of the answer: you shouldn't have to strip() after you call split() because split() will consider multiple whitespace characters as a single delimiter and automatically remove the extra whitespace. For example, this snippet evaluates to True:
s1 = "1 2 3"
s2 = "1 2 3"
s3 = " 1 2 3 "
s1.split() == s2.split() == s3.split()
split() and strip() are both attributes of string objects!
When you're confused by code that's been stuffed into one line, it often helps to unravel that code out over multiple lines to understand what it's doing
Your line of code can be unraveled like so:
user_input_str = input()
split_input_list = user_input_str.split()
stripped_input = split_input_list.strip() ### ERROR!!!
lst = list(map(int, stripped_input))
Clearly, you tried to access the strip() method of a list object, and you know that doesn't exist.
In your second example, you do
user_input_str = input()
split_input_list = user_input_str.split()
lst = list(map(int, split_input_list))
Which works perfectly fine because you don't try to access strip() on a list object
Now to fix this, you need to change the order of operations: first, you get your input. Next, strip it. This gives you back a string. Then, split this stripped string.
user_input_str = input()
stripped_input_str = user_input_str.strip() ### No error now!
split_input_list = stripped_input_str.split()
lst = list(map(int, split_input_list))
#or in one line:
lst = list(map(int, input().strip().split()))
Or, if you want to strip each element of the split input list, you will need to map the strip() function to split_input_list like so:
user_input_str = input()
split_input_list = user_input_str.split()
stripped_input_list = list(map(str.strip, split_input_list))
lst = list(map(int, stripped_input_list))
#or in one line
lst = list(map(int, map(str.strip, input().split())))
# or, create a function that calls strip and then converts to int, and map to it
def stripint(value):
return int(value.strip())
lst = list(map(stripint, input().split()))

python string split slice and into a list

I have a string for example "streemlocalbbv"
and I have my_function that takes this string and a string that I want to find ("loc") in the original string. And what I want to get returned is this;
my_function("streemlocalbbv", "loc")
output = ["streem","loc","albbv"]
what I did so far is
def find_split(string,find_word):
length = len(string)
find_word_start_index = string.find(find_word)
find_word_end_index = find_word_start_index + len(find_word)
string[find_word_start_index:find_word_end_index]
a = string[0:find_word_start_index]
b = string[find_word_start_index:find_word_end_index]
c = string[find_word_end_index:length]
return [a,b,c]
Trying to find the index of the string I am looking for in the original string, and then split the original string. But from here I am not sure how should I do it.
You can use str.partition which does exactly what you want:
>>> "streemlocalbbv".partition("loc")
('streem', 'loc', 'albbv')
Use the split function:
def find_split(string,find_word):
ends = string.split(find_word)
return [ends[0], find_word, ends[1]]
Use the split, index and insert function to solve this
def my_function(word,split_by):
l = word.split(split_by)
l.insert(l.index(word[:word.find(split_by)])+1,split_by)
return l
print(my_function("streemlocalbbv", "loc"))
#['str', 'eem', 'localbbv']

Python len not working

In the code below, I am trying to use len(list) to count the number of strings in an array in each of the tags variables from the while loop. When i did a sample list parameter on the bottom, list2, it printed 5 which works, but when i did it with my real data,it was counting the characters in the array, not the number of strings. I need help figuring out why that is and i am new to python so the simplest way possible please!
#!/usr/bin/python
import json
import csv
from pprint import pprint
with open('data.json') as data_file:
data = json.load(data_file)
#pprint(data)
# calc number of alert records in json file
x = len(data['alerts'])
count = 0
while (count < x):
tags = str(data['alerts'][count] ['tags']).replace("u\"","\"").replace("u\'","\'")
list = "[" + tags.strip('[]') + "]"
print list
print len(list)
count=count+1
list2 = ['redi', 'asd', 'rrr', 'www', 'qqq']
print len(list2)
Your list construction list = "[" + tags.strip('[]') + "]" creates a string, not a list. So yes, len works, it counts the characters in your string.
Your tags construction looks a bit off, you have a dictionary of data (data['alerts']) which you then convert to string, and strip of the '[]'. Why don't use just get the value itself?
Also list is a horrible name for your variable. This possible clashes with internal values.
list = "[" + tags.strip('[]') + "]"
print list
print len(list)
Ironically, list is a string, not a list. That's why calling len on it "was counting the characters in the array"
you need to make sure that your variable is a list rather than a str,
try:
print(type(yourList))
if it shows that it is a str, then try this:
len(list[yourList)
hope this answers your question
and when you want to establish a list variable, try this:
myList = []
for blah in blahblah:
myList.append(blah)
I think these definitely solved your problem, so I hope you noticed this part.

Categories