1.11M Members

remove a letter in a string

 
0
 

im making this game that is called PyTanks. If you want to know more about it please visit http://pythongaming.py.funpic.org/pythonmadegames.html
...

Anyway,

I ran across this problem, how do you delet or remove a letter from a string. Lets say that my string is-

string = "open sesame"

I want to remove the "n" in the string above. (letter 3 in string)
how do i do this:?:

 
0
 

Do you want to remove it by by index (3) or value ('n')?

To remove by index, you could do

s = s[:3] + s[4:]

which will give good results even if len(s) < 4.

If you want to remove by value, you could do

s = s.replace('n','')

(which will clobber all 'n's)

Jeff

 
0
 
s = "open sesame"
print s[0:s.index('n')] + s[ s.index('n') +1 : ]
 
0
 

If you just want to remove the first 'n' use:

old = "open sesame nnnn"
# replace first occurance of 'n'
new = old.replace('n', '', 1)
print new  # 'ope sesame nnnn'
 
0
 
s = "open sesame"
print s[0:s.index('n')] + s[ s.index('n') +1 : ]
>>> s='fred'
>>> print s[0:s.index('n')] + s[ s.index('n') +1 : ]

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in -toplevel-
    print s[0:s.index('n')] + s[ s.index('n') +1 : ]
ValueError: substring not found
>>>

:(

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article