-2

What is wrong with the following Python code for replacing "." with "-"

x = 'BRK.B'
if "." in x
    spot = x.find('.')
    x(spot)="-"
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
Leigh
  • 49
  • 1
  • 1
  • 9

2 Answers2

1

You have some typos, that makes your code unworkable.

Even if you fix this, x is a string, and string is not mutable.

You can just use str.replace.

 x = x.replace('.','-')
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • 4
    and this is supposed to be a comment! – Keerthana Prabhakaran Mar 07 '17 at 11:36
  • People often write the shortest answer that satisfies the OPs question, and then elaborate consistently. May be you people don't like that. – Ahsanul Haque Mar 07 '17 at 11:40
  • not really! And this is anyway a possible duplicate of http://stackoverflow.com/questions/1228299/change-one-character-in-a-string-in-python – Keerthana Prabhakaran Mar 07 '17 at 11:42
  • 1
    @KeerthanaPrabhakaran Really? How did it just "ask for more information or suggest improvements"? To me it looks like it was a (partial) answer, and we're explicitly told to "Avoid answering questions in comments". – Stefan Pochmann Mar 07 '17 at 11:50
  • There's nothing wrong with submitting a partial answer that you then add more detail to, but the initial answer _must_ be an adequate answer in its own right. – PM 2Ring Mar 07 '17 at 11:57
1

You could just use replace:

>>> 'BRK.B'.replace('.', '-')
'BRK-B'

If you only want to replace the first occurence :

>>> 'BRK.B'.replace('.', '-', 1)
'BRK-B'

If for some reason, you really want to do it yourself :

x = 'BRK.B'
if "." in x: # <- Don't forget : after x
    spot = x.find('.')
    # You're not allowed to modify x, but you can create a new string
    x = x[:spot] + '-' + x[spot+1:]
print(x)
# 'BRK-B'
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124