Subtract two strings in python

2024/10/7 15:19:00

I should calculate the difference between elements two different list. This is my code :

import operator
a   = ['5', '35.1', 'FFD']
b    = ['8.5', '11.3', 'AMM']      
difference = [each[0] - each[1] for each in zip(b, a)]
print difference

I need this output:

b-a = ['3.5','-23.8','AMM-FFD']

I receive the following error:

unsupported operand type(s) for -: 'str' and 'str'

I don't want to use any class like numpy or pandas

Answer

You need to convert numbers to floats, and if the elements cannot be converted to numbers, insert a '-' between them.

diffs = []
for i, j in zip(a, b):try:diffs.append(str(float(j) - float(i)))except ValueError:diffs.append('-'.join([j, i]))>>> print(diffs)
['3.5', '-23.8', 'AMM-FFD']

Since python is strongly typed (not to be confused with static vs. dynamic) it does not implicitly perform arithmetic on the numeric interpretation of strings if it encounters an arithmetic operator between strings. There is no obvious behavior of the minus operator with regard to strings the way there is an obvious behavior of plus (i.e., concatenate). Would you expect it to remove instances of the second string from the first string? If so, there's already a more explicit str.replace method you can use. Or would you expect it to remove the second string from the first only if the first string ends with the second string? The expected behavior isn't 100% obvious, so the python authors did not include __sub__ method support for strings.

Also, the operator module isn't used in your code, so no need to import it.

https://en.xdnf.cn/q/118807.html

Related Q&A

Python assignment for a phonebook

This weeks lab is based on the example on pages 53,54 of the wikibook "Non-Programmers Tutorial For Python" by Josh Cogliati (2005), (see http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutor…

ImportError: No module named application [duplicate]

This question already has answers here:What is __init__.py for?(14 answers)Closed 6 years ago.I am running a flask application and connecting to database with Flask-mysqlAlchemy when I am running my s…

Detect keypress without drawing canvas or frame on tkinter [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 6…

regex to extract a set number of words around a matched word

I was looking around for a way to grab words around a found match, but they were much too complicated for my case. All I need is a regex statement to grab, lets say 10, words before and after a matched…

How do I make a minimal and reproducible example for neural networks?

I would like to know how to make a minimal and reproducible deep learning example for Stack Overflow. I want to make sure that people have enough information to pinpoint the exact problem with my code.…

Increase the capture and stream speed of a video using OpenCV and Python [duplicate]

This question already has answers here:OpenCV real time streaming video capture is slow. How to drop frames or get synced with real time?(4 answers)Closed 2 years ago.I need to take a video and analyz…

Getting Pyphons Tkinter to update a label with a changing variable [duplicate]

This question already has answers here:Making python/tkinter label widget update?(5 answers)Closed 8 years ago.I have a python script which I have written for a Raspberry Pi project, the script reads …

Can someone help me installing pyHook?

I have python 3.5 and I cant install pyHook. I tried every method possible. pip, open the cmd directly from the folder, downloaded almost all the pyHook versions. Still cant install it.I get this error…

What is the bit-wise NOT operator in Python? [duplicate]

This question already has answers here:The tilde operator in Python(10 answers)Closed last year.Is there a function that takes a number with binary numeral a, and does the NOT? (For example, the funct…

PyQt QScrollArea no scrollarea

I haveclass View(QtWidgets.QLabel):def __init__(self):super(View,self).__init__()self.cropLabel = QtWidgets.QLabel(self)self.label = QtWidgets.QLabel(self)self.ogpixmap = QtGui.QPixmap()fileName = rC:/…