[Tutor] Loop not iterating

Steven D'Aprano steve at pearwood.info
Sun Jul 5 08:08:44 CEST 2015


Hi Nym, sorry your code's formatting is broken again. I've tried my best 
to fix it below:

On Fri, Jul 03, 2015 at 09:04:10PM +0000, Nym City via Tutor wrote:
> Thank to very much for replying.  The second solution that you proposed worked perfectly:
> 
> import csv
> domains = open('top500domains.csv')
> domainsReader = csv.reader(domains)
> domains = ["https://www." + row[1] for row in domainsReader]
> for domain in domains:
>    print(domain) 
> 
> The above solution is perfect and simple. It allows me to easily 
> insert text such as "https://www."  in the beginning of my strings or 
> at the end.
>
> However, something else that came to mind was how would you break the 
> string and insert new text in the middle. For 
> example:"www.lovepython.com" I want to insert "lesson1." after the 
> second period above. So it would come back as: 
> "www.lovepython.lesson1.com"

The most general way to do this is with string slicing. You have to 
build a new string:

s = "www.lovepython.com"
# find the 1st period
i = s.find('.')
# and the second:
i = s.find('.', i+1)
# slice just before the second dot
new_s = s[:i] + ".lesson1" + s[i:]
print(new_s)



> First I thought row[1] in the code above 
> referred to the first place in the beginning of the string. So I tried 
> to change that number around but it did not work. I have a feeling I 
> might be mixing few concepts together... Thank you.


row[1] refers to item 1 in the list row, it has nothing to do with dots 
in the string.

The best tool for learning Python is to play with the interactive 
interpeter. Start up Python to get a command prompt. By default, the 
prompt is ">>> " but I prefer to use "py> ". Now just type commands as 
needed. Python will automatically display them, or you can use print.


py> row = ["This", "that", "www.lovepython.com.au/", "blah blah"]
py> row[0]
'This'
py> row[2]
'www.lovepython.com.au/'
py> s = row[2]
py> s.find(".")  # first dot
3
py> s.find(".", 4)  # second dot
14
py> s[:14]  # slice up to the second dot
'www.lovepython'
py> s[14:]  # and from the second dot onwards
'.com.au/'


Here's another way to do it:

py> s = row[2]
py> L = s.split(".")
py> print(L)
['www', 'lovepython', 'com', 'au/']
py> L.insert(2, "lesson999")
py> print(L)
['www', 'lovepython', 'lesson999', 'com', 'au/']
py> s = '.'.join(L)
py> print(s)
www.lovepython.lesson999.com.au/


-- 
Steve


More information about the Tutor mailing list