-1

I'm a python new-comer, so there is probably a simple answer to this question, but I have looked and found nothing.

I want to define a function that when this is entered: "function(abcdefg123, fg1, " ")" the return is this: "abcde 23". I think it would look like this:

def function(something, what_to_deleat, what_to_substitute):
  if str(what_to_deleat) in str(something):
    return ## Code that replaces "what_to_deleat" with "what_to_substitute"  within "something"
  else:
    return something

A practical application (and the one I'm wanting to use this for) would convert 25.0 into 25 if 'function("25.0", ".0", "")' was entered.

Lewis
  • 23
  • 4
  • 1
    string.replace() method would do. Here https://www.pythoncentral.io/pythons-string-replace-method-replacing-python-strings/ – Aditya Jan 22 '18 at 18:44

1 Answers1

1

I guess the simplest solution would be

 def function(something, what_to_delete, what_to_substitute):
    return something.replace(what_to_delete, what_to_substitute)

Of course you would not need to write your own function here at all...

See https://docs.python.org/2/library/string.html#string.replace

wolff
  • 426
  • 4
  • 11
  • Thanks... so why doesn't this work? – Lewis Jan 22 '18 at 23:31
  • def cut(n): if str(n) == str(n).replace(".0", ""): return str(n).replace(".0", "") else: return str(n) – Lewis Jan 22 '18 at 23:31
  • I tried a bunch of things, but it either gives an error or doesn't do anything. e.g. cut(25.0) just gives 25.0, not 25 like I want. – Lewis Jan 22 '18 at 23:34