Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract strings in python

Tags:

python

Basically, if I have a string 'AJ' and another string 'AJYF', I would like to be able to write 'AJYF'-'AJ' and get 'YF'.

I tried this but got a syntax error.

Just on a side note the subtractor will always will be shorter than the string it is subtracted from. Also, the subtractor will always be like the string it is subtracted from. For instance, if I have 'GTYF' and I want to subtract a string of length 3 from it, that string has to be 'GTY'.

If it is possible, the full function I am trying to do is convert a string to a list based on how long each item in the list is supposed to be. Is there any way of doing that?

like image 983
jay a Avatar asked Mar 15 '17 00:03

jay a


People also ask

How do you subtract strings?

Reverse both strings. Keep subtracting digits one by one from 0'th index (in reversed strings) to the end of a smaller string, append the diff if it's positive to end of the result. If difference(diff) is negative then add 10 and keep track of carry as 1 if it's positive then carry is 0. Finally, reverse the result.

Can you minus strings in Python?

The Python string doesn't have a subtraction operator.

How do you subtract two strings in a list in Python?

To show the difference, list(Counter(a=1, b=2)) == ['a', 'b'] while list(Counter(a=1, b=2). elements()) == ['a', 'b', 'b'] .

How do you subtract in Python?

To subtract two numbers in Python, use the subtraction(-) operator. The subtraction operator (-) takes two operands, the first operand on the left and the second operand on the right, and returns the difference of the second operand from the first operand.


1 Answers

Easy Solution is:

>>> string1 = 'AJYF' >>> string2 = 'AJ' >>> if string2 in string1: ...     string1.replace(string2,'') 'YF' >>> 
like image 198
Shubham Namdeo Avatar answered Sep 17 '22 05:09

Shubham Namdeo