Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Tuesday, June 19, 2012

Removing punctuations


Python has a built-in function to access all the punctuations:

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

Code to remove punctuation(s) from a given string:

from string import punctuation
def removePunctuation(string,replacement='',exclude=''):
   for p in set(list(punctuation)).difference(set(list(exclude))):
       string = string.replace(p,replacement)
   return string

>>> removePunctuation("Hello World!!",' ')
"Hello World  "

>>> removePunctuation("Hello World!!")
"Hello World"

>>> removePunctuation("Hello-World!!",'  ','!')
"Hello World!!"

The replacement parameter replaces the punctuation characters with the given character.
The default value to replace punctuation marks is an empty string.

The exclude option provides scope to retain specific punctuations. For example in the case of cleaning a paragraph of text, we might want to retain the full stop (.) mark. The exclude parameter takes a string containing all the punctuations that needs to be skipped.

Wednesday, January 4, 2012

Split String Multiple Delimiters Python

The python function split([sep,[,maxsplit]]) is a good way to split a string for a given delimiter or sep. The delimiter may itself be composed of multiple characters. However, this function is insufficient when multiple delimiters are considered.

>>> l = "Birds;and,Bees"
>>> l.split(";,")
['Birds;and,Bees']

The way to achieve this is to use the regular expression package and use the re.split(pattern, string, maxsplit=0, flags=0) method available from the package.


>>> import re
>>> re.split(";|,",l)
['Birds', 'and', 'Bees']


The key is to use the "|" operator to indicate multiple delimiters.