[Tutor] Character Buffer Object Error
bob gailer
bgailer at gmail.com
Wed Feb 8 15:04:36 CET 2012
On 2/8/2012 12:56 AM, Michael Lewis wrote:
> I want to find all digits in a string and then increment those digits
> by 1 and then return the same string with the incremented digits.
[snip]
You got lots of good advice from others and some not-so-good advice.
Michael said:
2. The following line appears wrong.
new_output = ' '.join(user_input)
He did not say why!
I add:
Master the art of "Desk Checking".
Take pencil & paper.
Write down the input and output of each statement as though you were the
computer.
Also learn to read the & understand the Python Manuals:
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old
replaced by new. If the optional argument count is given, only the first
count occurrences are replaced.
Notice "return a copy". It does NOT say that this will convert old in place.
No one else caught this problem!
Since this is homework we we probably should not be offering alternative
solutions.
However I can't resist offering the one-line solution:
''.join(str(int(x)+1) if x.isdigit() else x for x in 'user_input)
--
Bob Gailer
919-636-4239
Chapel Hill NC
More information about the Tutor
mailing list