Python - How to Extract Text from List

My question is:

Extract: "agne"
From:    "Orange"

I am trying to extract not ange but agne from Orange. How do I change n and gf?

3

2 Answers

You can use the following to extract text from a list:

>>> fruit = 'Orange'
>>> print (fruit[2] + fruit[4] + fruit[3] + fruit[5])
agne

You can loop through the characters of extract and if the character is in word , append to a list then .join() the list into a str

Using list comprehension :

word = 'Orange'
extract = 'agne'
print(''.join([i for i in [*extract] if i in word]))
agne

Expanded loop:

new = []
for i in extract:
    if i in list(word):
        new.append(i)

new = ''.join(new)
print(new)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest