0

Using Python v2, is there a way to ignore a value in a string if it is there?

For instance: I want someone to enter a value of $100.00, or they could enter a value of 100.00 without the leading $ symbol. What I want to do is ignore the '$' value if it is typed in.

Any push in the right direction would be appreciated.

6 Answers 6

3

Maybe

s = "  $100.00 "
f = float(s.strip().lstrip("$"))

The .strip() strips whitespace from the beginning and the end of the string, and the .lstrip("$") strips a dollar sign from the beginning, if present.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the lstrip, I did not know about that either
1

If you only want to remove a '$' then s.replace('$', '') will do want you want.

If you want to replace more than one character then you need to chain replace calls together, which gets very ugly very quickly and in that case one of the other solutions is probably better.

Comments

1

Just filter out unwanted characters from the string. There are multiple ways of doing this, for clarity you could use:

def clean(s, wanted = "0123456789."):
  """Returns version of s without undesired characters in it."""
  out = ""
  for c in s:
    if c in wanted:
      out += c
  return out

To avoid the dynamic string-building, which is costly, you can build a list and then turn the list into a string:

def clean2(s, wanted = "0123456789."):
  outlist = [c for c in s if c in wanted]
  return "".join(outlist)

1 Comment

Extending a string using addition is tremendously slow and should be avoided at all costs. It's much better to add the characters to a list then use "".join(out) to turn it into a string.
0

You could simply use a regular expression to extract the number from the string.

Or your could be lazy if you just want to remove a leading $:

if s.startswith('$'):
    s = s[1:]

If you want to remove multiple $ signs, replace if with while or use s = s.lstrip('$')

PS: You might want to remove trailing $ signs, too. rstrip() or endswith() and s[:-1] are your friends in this case.

Comments

0

Just lstrip $ from the string before you process it.

value = ...
value = value.lstrip( ' $' ) # Strip blank and $

Comments

0
a = "$100.00"
b = ''.join((c for c in a if c != "$"))

of course this is reasonable if you don't know the position of the character you want to remove

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.