Edited: How would I go about returning/printing certain words between commas? (Python 3.41)

0 John Galecki · October 3, 2014
I have a text file that says



        i am section 1, i am section 2, i am section 3
        i am section 4, i am section 5, i am section 6
        i am section 7, i am section 8, i am section 9




How would I only print sections 1, 4, and 7 (the first section on a new line)?

Here is the code that I have so far.
    


        fp = open("text", "r+")
        titles = fp.read().split(',')
       l = list(titles)                #Trying to convert tuple to list
        print(titles[0,3,6])



Post a Reply

Replies

Oldest  Newest  Rating
0 Doug Fresh · October 4, 2014
your list is not a tuple, the positioning of your bounds is a tuple. 
fp = open("text", "r+")
titles = fp.read().split(',')
l = list(titles) #Trying to convert tuple to list
print(titles[0])


this should work.

I would probably run it with a loop. perhaps like this:


fp = open("text", "r+")

titles = fp.read().split(',')
sectionNumbers = (0,3,6)

for i in sectionNumbers:
try: ##This is a bit of defensive programming. I personally like to have it for the user's sake, and my sanity.
        print(titles)
    except IndexError:
        print("There is no information at that position")

fp.close()

This allows you to either set the bounds yourself before running the program, or you could even prompt the user for which sections you need. Don't forget to always .close() your files after opening them. 
0 Doug Fresh · October 4, 2014
Your list is not a tuple, the positioning is a tuple.


p = open("text", "r+")

titles = fp.read().split(',')
sectionNumbers = (0,3,10)

for i in sectionNumbers:
    try:
        print(titles)
    except IndexError:
        print("There is no information at that position")
    

fp.close()

when you write the code:

print(titles[0,3,6])

you are passing the positional argument in the form of a tuple, this argument only takes integers, ie, a separate call for each section. Basically, you need either a loop and a set of numbers to iterate through, or you need an individual print statement for each section.


print(titles[0])
print(titles[3])
print(titles[6])

 
  • 1

Python

106,949 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator