0

I have a list of elements whose text is like the following: aSampleElementText = "Vraj Shroff\nIndia" I want to have two lists now where the first list's element would have "Vraj Shroff" and the second list's element would have "India".

I looked at other posts about split and splitlines. However, my code below is not giving me expected results.

Output:

"V", 
"r"

Desired output:

"Vraj Shroff",
"India"

My code:

personalName = "Something" #first list
personalTitle = "Something" #second list
for i in range(len(names)-1) 
    #names is a list of elements (example above)
    #it is len - 1 becuase I don't want to do this to the first element of the list
    i += 1
    temp = names[i].text
    temp.splitlines()
    personName.append(temp[0])
    personTitle.append(temp[1])
3
  • What is names? And it looks like you are also missing a colon in your for loop. Commented May 17, 2018 at 4:55
  • @Rakesh I tried that. It does not work. I am new at Python. I am not really sure why that is the case. Commented May 17, 2018 at 4:57
  • @MoonCheesez it is a list of elements that I scraped. In the for loop, I am trying to access the title but in 2 lists. I will add the colon (it was present in the real code so that is not the issue) Commented May 17, 2018 at 4:58

2 Answers 2

1

names is a string. names[I] is the character corresponding to that index in the string. Hence you are getting this kind of output.

Do something like,

x = names.splitlines()

x will be the list with the elements.

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

1 Comment

aSampleElementText.splitlines()
0
names = []
locations = []
a = ["Vraj Shroff\nIndia", "Vraj\nIndia", "Shroff\nxyz", "abd cvd\nUS"]

for i in a:
    b = i.splitlines()
    names.append(b[0])
    locations.append(b[1])

print(names)
print(locations)

output:

['Vraj Shroff', 'Vraj', 'Shroff', 'abd cvd']
['India', 'India', 'xyz', 'US']

Is this what you were looking for?

Comments

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.