Reputation: 5769
I'm having problems splitting my names up by their listed order, name and their exam score.
I did the following in my code: print repr(names)
in a loop to get the following 6 lines of data
'1 Name 559/1 '
'2 Name 484/1 '
'3 Name N'ame 444/2 '
'4 Name 400/1 '
'5 Name Name 928/5 '
'6 Name Name-Name 1292/10 '
I want to be able to split them up but I get an error saying AttributeError: 'str' object has no attribute 'lsplit'
I've had a go using lsplit, rsplit and split but I can't get it to work...
In the end result names will be turned into 3 variables: names_index
, name
and names_score
Anyone know how I can acheive this?
Thanks - Hyflex
EDIT
for item in listitems:
if item.find("strong"):
names = str(item.text)
names = items .split("\n")
for name in names:
clean_name = name.lstrip(" ")
print repr(clean_name)
student_number = clean_name.lsplit(" ", 1)
student_score = clean_name.rsplit(" ", 1)
#student_name = clean_name.lsplit(" ", 1) # Unsure how to get the last part..
Upvotes: 2
Views: 13358
Reputation: 9107
rsplit returns the splitted result, not only the last part. So you are actually going in the right direction.
For your code where you might have space in your name, you can do this:
the_string = the_string.strip()
[id, name_score] = the_string.split(' ',1) # Split into ['1', 'name name 654/1']
[name, score] = name_score.rsplit(' ',1) # Split into ['name name','654/1']
so, for input `6 Name Name-Name 1292/10' your intended values are already there:
id # this is '6'
name # this is 'Name Name-name'
score # this is '1292/10'
Upvotes: 3
Reputation: 59974
There is no str.lsplit
because str.split
already goes from the left.
For each string, just call .split()
and you will get a list with [names_index, name, names_score]
If the pattern is number / words / more numbers
, then you can use regular expressions:
>>> import re
>>> filter(None, re.split(r'(\d+) (\w.*) (\d.*)', '1 Name 559/1 '))
['1', 'Name', '559/1 ']
>>> filter(None, re.split(r'(\d+) (\w.*) (\d.*)', '6 Name Name-Name 1292/10 '))
['6', 'Name Name-Name', '1292/10 ']
Upvotes: 5
Reputation: 26333
you can operate this way with your list
>>> names = ['1 Name 559/1 ',
'2 Name 484/1 ',
'3 Name Naaame 444/2 ',
'4 Name 400/1 ',
'5 Name Name 928/5 ',
'6 Name Name-Name 1292/10 ']
>>> names_lst=[]
>>> for n in names:
names_lst+=n.split()
gives
>>> names_lst
['1', 'Name', '559/1', '2', 'Name', '484/1', '3', 'Name', 'Naaame',
'444/2', '4', 'Name', '400/1', '5', 'Name', 'Name', '928/5', '6', 'Name',
'Name-Name', '1292/10', ['1', 'Name', '559/1'], ['2', 'Name', '484/1'],
['3', 'Name', 'Naaame', '444/2'], ['4', 'Name', '400/1'],
['5', 'Name', 'Name', '928/5'], ['6', 'Name', 'Name-Name', '1292/10']]
Upvotes: 3
Reputation: 7867
Its as easy as -
>>> s = '4 Name 400/1 '
>>> names_index, name, names_score = s.split()
>>> names_index, name, names_score
('4', 'Name', '400/1')
>>>
As Haidro said, there is no function as lsplit, use split instead.
Upvotes: 3