ChocoPython
ChocoPython

Reputation: 65

How do I remove certain character in a string?

Is there a method to do so? This is the code I have written. Also, I am using the latest version of Python:

import string

Finn = "It's Adventure Time!"
punctuation = string.punctuation
print(punctuation)
for punc in punctuation:
   if punc in Finn:
       Finn[18] = ' '
print(Finn)

Error I am getting is:

TypeError: 'str' object does not support item assignment

Upvotes: 1

Views: 1293

Answers (3)

PeterE
PeterE

Reputation: 5855

One very short variant is:

import string

finn = "It's Adventure Time!"
print(finn)
table = str.maketrans("","",string.punctuation)
finn = finn.translate(table)
print(finn)

This solution requires python 3. (As tagged in the OP)

Upvotes: 0

Dave J
Dave J

Reputation: 485

Shortest one, I can think of :P

import string
finn = "It's Adventure Time!"
finn = ''.join(i for i in finn if i not in string.punctuation)

Upvotes: 0

Shahriar
Shahriar

Reputation: 13804

I hope you are expecting this:

import string

Finn = "It's Adventure Time!"
punctuation = string.punctuation
print(punctuation)
for punc in punctuation:
   if punc in Finn:
       Finn = Finn.replace(punc, "")

print(Finn)

Upvotes: 1

Related Questions