0

My Code is splitting up a file line by line into strings and extends them to a list.

I noticed that for cases where only one string is extended, the result will split up that string and extend it letter by letter to the empty list. If I delete [-1] the string remains intact, but the other strings will be extended aswell.

How can I prevent that string from being split up when extending it to the empty list?

searchstring = "abc dfe ghi"     #resembles a searchline from a file
text = searchstring.split()          #note: same thing happens if i add [-1] here
list1.extend(text[-1])           #I only want the last element of the string

So either the output is:

print list1
[abc, dfe, ghi]

or

print list1
[g, h, i]

but I need it this way

print list1
[ghi]             #one entry for each line in the file
6
  • I have not understood what you're trying to achieve Commented Jun 16, 2017 at 15:58
  • 1
    Can you provide a complete example? Are your abc, dfe, ghi supposed to be string literals? It will be easier to help you if you could provide exact code which fully replicates your problem as well as the intended output. Commented Jun 16, 2017 at 15:58
  • 1
    @AlexAlifimoff: meta.stackoverflow.com/a/256331/2988730 Commented Jun 16, 2017 at 15:59
  • 1
    @MadPhysicist: I can't cast close votes so I do what is within my abilities to help as best as possible. Commented Jun 16, 2017 at 16:02
  • 1
    @AlexAlifimoff. Thanks. I'm glad you did that and I'm glad OP listened. I have now retracted my close vote thanks to both of you. Commented Jun 16, 2017 at 16:03

1 Answer 1

4

list.extend accepts an iterable.

So when you pass it a string (ghi) it uses it like a list, extending list with chars from that string.

You may want to put that string to a list or use list.append.

Sign up to request clarification or add additional context in comments.

1 Comment

solved: list.append works. I already used it somewhere else in the code, but sometimes you just dont find the obvious solution. Thanks! (stackoverflow wont let me mark your answear as solution for the next 5 min)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.