0

I have the following list:

sentence = ['doc1','doc2','doc3','doc4']

How can I concatenate .txt at the end of each elment of sentece? (*):

['doc1.txt','doc2.txt','doc3.txt','doc4.txt']

I tried to list comprehension:

'.txt '.join(sentence[:-1])

Nonetheless, it returns this:

'doc1.txt doc2.txt doc3'

Which is wrong, since it's different from (*)

3 Answers 3

2

You aren't trying to join the whole string together just add .txt to each string:

>>> [s + '.txt' for s in sentence]
['doc1.txt', 'doc2.txt', 'doc3.txt', 'doc4.txt']

Not sure why you are slicing off the last element.

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

1 Comment

I see... thanks for helping me to clarify this issue.
2

Another approach :

>>> sentence = ['doc1','doc2','doc3','doc4']
>>> list(map(lambda x : x + '.txt', sentence))
['doc1.txt', 'doc2.txt', 'doc3.txt', 'doc4.txt']

Comments

1

You may use map and lambda

map(lambda x:x+'.txt', sentence)

output:

['doc1.txt', 'doc2.txt', 'doc3.txt', 'doc4.txt']

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.