0

['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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

Nope getting [' '] as the output. And i want to do this one by one. For example a = mylist[1] where mylist[1] = ''2016-11-30 11:43:32 62944 UserID-12345.jpg\n' and then extract anpr.jpg from it.
Well, my answer respond at the input you gave. If you have another input please edit your question and i'll update my answer.
check the question.
Is it articulate enough?
Check now. Did it fill your needs ?

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.