简体   繁体   中英

How to extract a substring from a string?

a = ['google.com', 'bing.com', 'yahoo.co.in']

Output = ['.com', '.in']

How do I get this output without using regular expressions?

Tried using nested for loop and partition function but could not get the output.

Try this:

output = set(f".{w.split('.')[-1]}" for w in a)

Or

set(["."+ x.rsplit('.', 1)[-1] for x in a])

Or using pop()

set(["."+ x.rsplit('.', 1).pop() for x in a]))

It is possible to do this using nested for loop. Try this:

a = ['google.com','bing.com','yahoo.co.in']
output = []
for ele in a:
    count = 0
    for char in reversed(ele):
        count += 1
        if char == '.':
            break
        
    word = ele[-1*count:]
    if word not in output:
        output.append(word) 

print(output)

you could try:

a = ['google.com', 'bing.com', 'yahoo.co.in']
output = []
for domain in a:
    suffix = '.' + str(domain.split('.')[-1])
    if not suffix in output:
        output.append(suffix)
    

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