Why am I unable to strip '$' in the first method of code however I am able to strip in the second method?
Method 1
sales = ['$1.21', '$7.29', '$12.52', '$5.13', '$20.39', '$30.82', '$1.85', '$17.98', '$17.41', '$28.59']
for element in sales:
element.strip('$')
print(element)
Method 2
sales = ['$1.21', '$7.29', '$12.52', '$5.13', '$20.39', '$30.82', '$1.85', '$17.98', '$17.41', '$28.59']
for element in sales:
print(element.strip('$'))
You need to assign the variable in the for loop and use indexing if you want to change the original list:
sales = ['$1.21', '$7.29', '$12.52', '$5.13', '$20.39', '$30.82', '$1.85', '$17.98', '$17.41', '$28.59']
for x in range(len(sales)):
sales[x] = sales[x].strip('$')
print(sales[x])
It seems like you'd like to treat sales as a numeric variable
sales = ['$1.21', '$7.29', '$12.52', '$5.13', '$20.39', '$30.82', '$1.85', '$17.98', '$17.41', '$28.59']
sales = [float(element.strip('$')) for element in sales]
Then you could either print it or sum it
print("total sales: {t:.2f}".format(t=sum(sales)))
str.strip method does not modify given string, instead it returns the result as it is specified in official documentation.
Return a copy of the string with the leading and trailing characters removed.
Since element.strip('$')
returns result instead of modifying element
this code does nothing.
To convert it into cents (don't ever do currency work with floats since floats are imprecise, you can do this:
sales_in_cents = [int(element.strip('$').replace('.','')) for element in sales]
To show the total in $...
print(f'Total sales : {sum(sales_in_cents)/100:0.2f}'
Do all of your calculations (including your sums) with cents and convert to $ (by dividing by 100 only when you need to do so.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.