We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,809 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Split String Problem

Hey. I'm pretty new in Python. I'm trying to read from my file all the content and put it in a string. My file looks:

1 string1
2 string2
10 string 3

and I want to obtain: ["1", "string1", "2", "string 2", "10", "string3"] using this:

def read(self):
        file = open("Repository/file.txt", 'r')
        f = file.readlines()
        f = f.split(" ")
        print f

but I get this: AttributeError: 'list' object has no attribute 'split'

Thanks!

3
Contributors
2
Replies
18 Minutes
Discussion Span
1 Year Ago
Last Updated
3
Views
Question
Answered
mr_noname
Newbie Poster
1 post since Feb 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Use f = file.read() and f = f.split() .

Gribouillis
Posting Maven
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11
Question Answered as of 1 Year Ago by Gribouillis
with open('numb.txt') as f:
    print [i.split() for i in f]
    #[['1', 'string1'], ['2', 'string2'], ['10', 'string3']]

A little mistake like this for 1 list.

with open('numb.txt') as f:
    print f.read().split()
    #['1', 'string1', '2', 'string2', '10', 'string3']
snippsat
Posting Shark
956 posts since Aug 2008
Reputation Points: 482
Solved Threads: 344
Skill Endorsements: 8

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0807 seconds using 2.63MB