2

Im trying to make a Hangman game and I need to change certain characters in a string. Eg: '-----', I want to change the third dash in this string, with a letter. This would need to work with a word of any length, any help would be greatly appreciated

crhodes
  • 1,178
  • 9
  • 20
William Smith
  • 137
  • 2
  • 3
  • 11
  • 2
    See: [change-one-character-in-a-string-in-python](http://stackoverflow.com/questions/1228299/change-one-character-in-a-string-in-python) – j.f. Aug 13 '14 at 17:48
  • @j.f. is correct. Strings cannot be changed in Python, unlike Java or C. You should convert the string to a list, and then you can modify that list character by character. – TheSoundDefense Aug 13 '14 at 17:51

3 Answers3

2

Strings are immutable, make it a list and then replace the character, then turn it back to a string like so:

s = '-----'
s = list(s)
s[2] = 'a'
s = ''.join(s)
crhodes
  • 1,178
  • 9
  • 20
0
String = list(String)
String[0] = "x"
String  = str(String)

Will also work. I am not sure which one (the one with .join and the one without) is more efficient

Ethan McCue
  • 883
  • 1
  • 8
  • 17
0

You can do it using slicing ,

>>> a
'this is really string'
>>> a[:2]+'X'+a[3:]
'thXs is really string'
>>> 
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81