954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Take out punctuation from a string and print it.

Implement a function punctuation() that takes no parameters, inputs a string from the user, and prints all of the punctuation characters appearing in the string, in order from left to right.

My coding I have so far is:

def punctuation():
a = raw_input("Please enter a string:")
check = ['!', ',', '.', ':', '?', ';']
for p in check:
if p in a:
a.remove(p)

I'm working on IDLE and I keep getting an error message saying raw_input isn't defined? Any help you guys could give me is appreciated!

pythonn00b
Newbie Poster
1 post since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

A little help.

>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>>

In this code i excludestring.ascii_letters

import string

exclude = string.ascii_letters
s = 'test.. hi? for ,,,'
punc_text = ''.join(ch for ch in s if ch not in exclude)
print punc_text #.. ?  ,,,
I keep getting an error message saying raw_input isn't defined?


If you are using python 3 changeraw_input() to input()
a.remove(p) will never work because string method dos not have a remove method.

snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
 

You can also use re to remove all characters with the W flag.
:)

richieking
Master Poster
764 posts since Jun 2009
Reputation Points: 61
Solved Threads: 152
 
You can also use re to remove all characters with the W flag.


Just to give a little more info about this.
richieking is talking about regular expression. http://docs.python.org/library/re.html

Her is a demo of how it work.
Using findall is an easy option,search and match are to other option to read about.

>>> import re
>>> r = re.findall(r'\W', 'test.. hi? for ,,,')
>>> r
['.', '.', ' ', '?', ' ', ' ', ',', ',', ',']
>>> #Make it a string
>>> ''.join(r)
'.. ?  ,,,'
>>>
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: