Reputation: 327
['PRE user_1/\n', '2016-11-30 11:43:32 62944 UserID-12345.jpg\n', '2016-11-28 10:07:24 29227 anpr.jpg\n', '2016-11-30 11:38:30 62944 image.jpg\n']
I have a list of string and i want to extract the 'name\n' part from each element and store it. For example i want to extract 'name\n' from mylist[0], where mylist[0] = 'PRE user_/n'. So user_1/
will be extracted and stored in a variable.
mylist = ['PRE user_1/\n', '2016-11-30 11:43:32 62944 UserID-12345.jpg\n', '2016-11-28 10:07:24 29227 anpr.jpg\n', '2016-11-30 11:38:30 62944 image.jpg\n']
for x in mylist:
i = 0
userid = *extract the 'name\n' from mylist[i]
print userid
i = i+1
How do i do this? Is Regular Expressions the way to do it?, if yes how do i implement it? A code snippet would be very helpful.
Upvotes: 0
Views: 718
Reputation: 9257
Maybe you can do it without regex
. You can try my solution:
a = ['PRE user_1/\n', '2016-11-30 11:43:32 62944 UserID-12345.jpg\n', '2016-11-28 10:07:24 29227 anpr.jpg\n', '2016-11-30 11:38:30 62944 image.jpg\n']
def get_name(arg = ""):
b = arg.split(" ")
for i in b:
if "\n" in i:
return i.replace("\n", "")
Output:
print get_name(a[0])
user_1/
print get_name(a[1])
UserID-12345.jpg
print get_name(a[2])
anpr.jpg
print get_name(a[3])
image.jpg
Also in order to fill the example you gave, your code will be:
for x in a:
userid = get_name(x)
print userid
Output:
user_1/
UserID-12345.jpg
anpr.jpg
image.jpg
Upvotes: 1