[Tutor] Iteration issues

Mats Wichmann mats at wichmann.us
Thu Jun 7 18:56:22 EDT 2018


On 06/07/2018 04:21 PM, Roger Lea Scherer wrote:
> I've given up again. I've tried the python documentation, I've tried to
> implement the above suggestions, I've tried the translate thing with a
> table that I did not include this time because I couldn't get it to work,
> I've looked at StackOverflow, Quora and another website, so many things
> seem so promising, but I just can't get them to work nor figure out why
> they won't. I've started from scratch again.
> 
> **********
> import string
> 
> gettysburg =
> open("C:/Users/Roger/Documents/GitHub/LaunchCode/gettysburg.txt", "r")
> 
> puncless = ""
> for char in gettysburg:
>     if char in string.punctuation:
>         gettysburg.replace(char, "")
>     else:
>         puncless += char
> print(puncless)
> 
> **********
> 
> The "puncless" part works fine, except it does not replace the punctuation
> like I expect and want.

You're doing multiple things, and they're not agreeing.

somestring.replace() returns a new string with the replacement done. but
you don't ever do anything with that new string. also you're writing as
if you do the replacement character-by-character, but replace() operates
on the whole string (or if you give it the extra count arguments, on
only the first count instances of your substring), and strings
themselves are immutable, so it is never changed. replace() is also
harmless if the substring is not found, so you could try this, for example:

for char in string.punctuation:
    gettysburg = gettysburg.replace(char, "")
print(gettysburg)

each time through that you get a *new* gettysburg with replacement done
on it, with the old one being lost due to no more references - you are
not actually ever modifying gettysburg itself.





> 
> Thank you for all your help already, but I need some more if you have any.
> :) Thanks.
> 
> On Sat, May 12, 2018 at 12:40 AM, Peter Otten <__peter__ at web.de> wrote:
> 
>> Neil Cerutti wrote:
>>
>>> punctuation_removal_table = str.maketrans({c: None for c in
>>> string.punctuation})
>>
>> Alternative spellings:
>>
>>>>> from string import punctuation
>>>>> (str.maketrans({c: None for c in punctuation})
>> ...  == str.maketrans(dict.fromkeys(punctuation))
>> ...  == str.maketrans("", "", punctuation))
>> True
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
> 
> 
> 



More information about the Tutor mailing list