1,105,344 Community Members

remove a letter in a string

Member Avatar
the_python
Newbie Poster
1 post since Mar 2007
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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:?:

Member Avatar
jrcagle
Practically a Master Poster
608 posts since Jul 2006
Reputation Points: 77 [?]
Q&As Helped to Solve: 160 [?]
Skill Endorsements: 0 [?]
 
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

Member Avatar
ghostdog74
Junior Poster
156 posts since Apr 2006
Reputation Points: 57 [?]
Q&As Helped to Solve: 48 [?]
Skill Endorsements: 0 [?]
 
0
 
s = "open sesame"
print s[0:s.index('n')] + s[ s.index('n') +1 : ]
Member Avatar
Ene Uran
Posting Virtuoso
1,822 posts since Aug 2005
Reputation Points: 610 [?]
Q&As Helped to Solve: 278 [?]
Skill Endorsements: 10 [?]
 
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'
Member Avatar
jrcagle
Practically a Master Poster
608 posts since Jul 2006
Reputation Points: 77 [?]
Q&As Helped to Solve: 160 [?]
Skill Endorsements: 0 [?]
 
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 three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article