How do you subtract two strings in python?

Discussions

Categories

How do you subtract two strings in python?

Hi,

I have two strings in format 'hh:mi:ss', I want subtract those two strings in the analysis.

First I tried to convert the strings with cast to a timestamp, but I get an error. Then I think maybe I must create a function which makes from this format numbers, subtract them and then convert it back to format hh:mi:ss.

But I think that is not a good solution, so my question is: Can I substract two strings

Example:

String 1 - String 2 = Result

02:38:16 - 00:07:15 = 02:31:01

With regards,

Ed

You can do this as long as you use well-formed lists:

s0 = "lamp, bag, mirror"
s = s0.split(", ") # s is a list: ["lamp", "bag", "mirror"]

If the list is not well-formed, you can do as follows, as suggested by @Lattyware:

s = [item.strip() for item in s0.split(',')]

Now to delete the element:

s.remove("bag")
s
=> ["lamp", "mirror"]

Either way - to reconstruct the string, use join():

", ".join(s)
=> "lamp, mirror"

A different approach would be to use replace() - but be careful with the string you want to replace, for example "mirror" doesn't have a trailing , at the end.

s0 = "lamp, bag, mirror"
s0.replace("bag, ", "")
=> "lamp, mirror"

Hi all, sorry if this is a dumb quesiton but just started python:

The exercise asks to write a function remove_vocals that takes the string from input, removes the vocals and returns a string with all the remaining characters.

my code up to now is

word= str(input('Insert characters:'))
vocals=('aeiou')
def remove_vocals(word,vocals):
    for i in range(len(word)):
        if word[i] == 'a'or'e'or'i'or'o'or'u':
            word=word-word[i]
            print(word)
remove_vocals(word,vocals)

but, unlike addition of strings i'm not able to perform a subtraction

Eg: print ('3' +'3') gives 33 print ('3' - '3') gives error

What do you expect from subtracting string? In your case do you expect an empty string? What about "334"-"3", "abc"-"&", "1244"-"4421"? Well, if there is a rule of subtracting string, it would hardly make sense. To remove a part of the string, you can use slice.

How do you subtract two strings in python?

The class string did not implement it. https://code.sololearn.com/cJLVkXZN1Vlw/?ref=app

How do you subtract two strings in python?

String subtraction makes no sense, but if you want results like these: "ABC" - "BC" = "A" "ABC" - "AB" = "C" then you can use str.replace method: "ABC".replace("BC", "") = "A" "ABC".replace("AB", "") = "B" str1.replace(str2, str3) gives a copy of string str1, where all occurences of substrings str2 will be replaced with substrings str3.

How do you subtract two strings in python?

Because "+" is not only a mathematical operator for summing numbers, but also a concatenation operator that concatenates strings.

How do you subtract two strings in python?

LoL! + operator on string doesn't add them It concatenate two strings. And - sign gives error because programmer of PYTHON didn't add that in syntax

How do you subtract two strings in python?

That's not addition, it is concatenation...

How do you subtract two strings in python?

How do you subtract two strings in python?

Difference of two large numbers,Sum of two large numbers,Check if binary representations of two numbers are anagram,Print number of words, vowels and frequency of each character


Suggestion : 2

Is there a way to split the string across say "bag," and somehow use that as a subtraction? Then I still need to figure out how to add., 1 good point ... really the split is probably the "correct" answer, however I figured I would throw this out there. not sure what languages support string subtraction or how it would behave in said languages – Joran Beasley Aug 26, 2013 at 23:33 ,I was wondering if I can add or subtract some items, in other programming languages I can easily do: str=str-"bag," and get str="lamp, mirror," this doesnt work in python (I'm using 2.7 on a W8 pc),Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

you could also just do

print "lamp, bag, mirror".replace("bag,", "")

How about this?

def substract(a, b):
   return "".join(a.rsplit(b))

You can do this as long as you use well-formed lists:

s0 = "lamp, bag, mirror"
s = s0.split(", ") # s is a list: ["lamp", "bag", "mirror"]

If the list is not well-formed, you can do as follows, as suggested by @Lattyware:

s = [item.strip() for item in s0.split(',')]

Now to delete the element:

s.remove("bag")
s
   => ["lamp", "mirror"]

you should convert your string to a list of string then do what you want. look

my_list = "lamp, bag, mirror".split(',')
my_list.remove('bag')
my_str = ",".join(my_list)

If you have two strings like below:

t1 = 'how are you'
t2 = 'How is he'

and you want to subtract these two strings then you can use the below code:

l1 = t1.lower().split()
l2 = t2.lower().split()
s1 = ""
s2 = ""
for i in l1:
   if i not in l2:
   s1 = s1 + " " + i
for j in l2:
   if j not in l1:
   s2 = s2 + " " + j

new = s1 + " " + s2
print new


Suggestion : 3

Now, how do we solve this? The simplest way is to use a lib- but if you can't do that, use a string. Strings are almost infinite in length, therefore you can use them to store large "numbers".,To subtract 2 numbers, you subtract each digit individually and carry over the borrows. This is the same case in programming. You just loop through the reversed string!,First, we need to make sure both of our numbers are the same length. To do this, we pad them with 0's. We can create a simple function for this:,Then, we want to subtract them. Here, we also want to subtract the borrowed number, if any.

First, we need to make sure both of our numbers are the same length. To do this, we pad them with 0's. We can create a simple function for this:

string makeThemSameLength(string s1, int n) {
   for (int i = 0; i < n; i++) {
      s1 = '0' + s1;
   }
   return s1;
}

Next, we need to be able to subtract single digits and return the borrowed and digits. To do this, we need to declare a structure.

struct SubDigResult {
   int r;
   int b;
};

In this structure, r is the result and b is borrow. Let's implement the function. We want this function to take in 3 chars and return a SubDigResult. Hence, we have this:

struct SubDigResult subDigits(char c1, char c2, int b) {}


Suggestion : 4

The Python string doesn't have a subtraction operator. If you want to get the difference of strings, here is a simple and understandable way., Subtract a string from another string ,You can iterate all letters in a string using the for statement and check a string contains a letter by the if-in statement. The s is x - y or the difference of x and y. The t is y - x or the difference of y and x., Get the index of the last occurrence of a substring

The Python string doesn't have a subtraction operator. If you want to get the difference of strings, here is a simple and understandable way.

x = 'abcd'
y = 'cdefg'

s = ''
t = ''

for i in x:
   if i not in y:
   s += i

for i in y:
   if i not in x:
   t += i

print(s) # ab
print(t) # efg


Suggestion : 5

IS there a way to subtract two strings?,[Its fine if string2 has any extra characters since that will be invalidated. The main string here is string1] .,What I thought of doing is to find the elements that match in each sentence and then subtract the strings and get the words which dont match. I was close to the solution with a normal for loop and if else but I couldnt pass the cases where a character would repeat . Can post code if needed,Basic Algorithm Scripting: Mutations | freeCodeCamp.org This is what im working on right on. I know that there might be a LOT of ways to solve this, maybe even ones which end in a few lines.

Sample Code:-

let string1 = 'heeloo';
let string2 = 'helo';
let subtractStr = string1 - string2;

function mutation(arr) {

   let replaceWords = arr[0].toLowerCase();

   let string2 = arr[1].toLowerCase();

   let increment = 0;

   for (let i = 0; i < string2.length; i++) {

      if (replaceWords.includes(string2[i])) {

         increment += 1;

      }

   }

   if (increment >= string2.length) {

      return true;

   } else {

      return false;

   }

}

console.log(mutation(["hello", "hey"]));


Suggestion : 6

I have a long string, which is basically a anycodings_addition list like str="lamp, bag, mirror," (and anycodings_addition other items),Is there a way to split the string across anycodings_addition say "bag," and somehow use that as a anycodings_addition subtraction? Then I still need to figure out anycodings_addition how to add.,and you want to subtract these two anycodings_python strings then you can use the below code:,you should convert your string to a list anycodings_python of string then do what you want. look

you could also just do

print "lamp, bag, mirror".replace("bag,", "")

How about this?

def substract(a, b):
   return "".join(a.rsplit(b))

You can do this as long as you use anycodings_python well-formed lists:

s0 = "lamp, bag, mirror"
s = s0.split(", ") # s is a list: ["lamp", "bag", "mirror"]

If the list is not well-formed, you can anycodings_python do as follows, as suggested by anycodings_python @Lattyware:

s = [item.strip() for item in s0.split(',')]

Now to delete the element:

s.remove("bag")
s
   => ["lamp", "mirror"]

you should convert your string to a list anycodings_python of string then do what you want. look

my_list = "lamp, bag, mirror".split(',')
my_list.remove('bag')
my_str = ",".join(my_list)

If you have two strings like below:

t1 = 'how are you'
t2 = 'How is he'

and you want to subtract these two anycodings_python strings then you can use the below code:

l1 = t1.lower().split()
l2 = t2.lower().split()
s1 = ""
s2 = ""
for i in l1:
   if i not in l2:
   s1 = s1 + " " + i
for j in l2:
   if j not in l1:
   s2 = s2 + " " + j

new = s1 + " " + s2
print new


Suggestion : 7

const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
console.log(getDifferenceInDays(date1, date2));
console.log(getDifferenceInHours(date1, date2));
console.log(getDifferenceInMinutes(date1, date2));
console.log(getDifferenceInSeconds(date1, date2));

function getDifferenceInDays(date1, date2) {
   const diffInMs = Math.abs(date2 - date1);
   return diffInMs / (1000 * 60 * 60 * 24);
}

function getDifferenceInHours(date1, date2) {
   const diffInMs = Math.abs(date2 - date1);
   return diffInMs / (1000 * 60 * 60);
}

function getDifferenceInMinutes(date1, date2) {
   const diffInMs = Math.abs(date2 - date1);
   return diffInMs / (1000 * 60);
}

function getDifferenceInSeconds(date1, date2) {
   const diffInMs = Math.abs(date2 - date1);
   return diffInMs / 1000;
}

const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log(diffTime + " milliseconds");
console.log(diffDays + " days");

function findDayDifference(date1, date2) {
   
   return Math.floor((Math.abs(date2 - date1)) / (1000 * 60 * 60 * 24));
}


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

How to subtract two lists in Python.
list1 = [2, 2, 2].
list2 = [1, 1, 1].
difference = [] initialization of result list..
zip_object = zip(list1, list2).
for list1_i, list2_i in zip_object:.
difference. append(list1_i-list2_i) append each difference to list..
print(difference).

Can we subtract 2 strings?

Strings are almost infinite in length, therefore you can use them to store large "numbers". To subtract 2 numbers, you subtract each digit individually and carry over the borrows. This is the same case in programming.

How do you subtract two string numbers?

Given two numbers as 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. ... .
Finally, reverse the result..

How do you subtract part of a string in Python?

Remove a part of a string in Python.
Remove a substring by replacing it with an empty string. ... .
Remove leading and trailing characters: strip().
Remove leading characters: lstrip().
Remove trailing characters: rstrip().
Remove prefix: removeprefix() (Python 3.9 or later).
Remove suffix: removesuffix() (Python 3.9 or later).