简体   繁体   中英

How do i extract a sub string which is composed of certain characters from a string in python?

For example, suppose I have a string "beabeefeab". I want to extract a substring which is composed of only 'b' and 'a' that is "babab".

I applied brute force by implementing a nested loop and deleting all characters but 'b' and 'a'

You can do it using a simple list comprehension

a = "beabeefeab"
print("".join([i for i in a if (i == 'a' or i =='b')]))

Output:

babab

Not very elegant, but it works.

a = "beabeefeab"
answer = ""
for char in a:
    if char == "a" or char == "b":
        answer += char

print(answer)

Output

babab

Using a set to keep the allowed chars, making this a bit more extensible:

s = "beabeefeab"
allowed = set('ab')
print("".join(x for x in s if x in allowed))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM