[Tutor] finding sum of digits in a string

Dennis Lee Bieber wlfraed at ix.netcom.com
Tue Mar 15 10:05:56 EDT 2022


On Tue, 15 Mar 2022 15:28:13 +1300, dn <PythonList at DancesWithMice.info>
declaimed the following:


>Alternate solution:
>The spec biases one's thinking by its use of the words: "the ...
>digits". Instead of that fixation, could we consider something like
>using translate() to replace any undesired characters with NULSTRING or
>zero, and then adding the digits/all that remains?

	Which leads me to the nightmare I envisioned overnight. Taking common
phone number formats and stripping down to just digits... While also
translating those fancy "word-based" phone numbers.

	Hadn't realized translate() allows one to "remove" (your NULSTRING)
case... But that is in the documentation... I'd expected to convert things
to spaces, split on space, then join on ""


>>> phone_numbers = [	"+1 (616) 987-5555",
... 			"1 (800) CALL-SAM",	#Sam Bernstein law offices
... 			"TW7-5555"	]	#old 60s "TWin oaks" exchange
... 			
>>> trans_table = "".maketrans("abcdefghijklmnopqrstuvwxyz",
... 				"22233344455566677778889999",
... 				"+()- ")
>>> for pn in phone_numbers:
... 	print("Pure phone #: %s" % pn.lower().translate(trans_table))
... 
Pure phone #: 16169875555
Pure phone #: 18002255726
Pure phone #: 8975555
>>> 


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/



More information about the Tutor mailing list