import re
p = "The pen is on the table."
def repl(x):
	if x.group(1):
		return "B{}".format("I"*len(x.group(2)))
	elif x.group(3):
		return "B"
	else:
		return "S"
		
print( re.sub(r'(\w)(\w*)|([^\w\s])|\s', repl, p) )
# => BIISBIISBISBISBIISBIIIIB
