'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.
Solution 1:[1]
Try this:
output = set(f".{w.split('.')[-1]}" for w in a)
Solution 2:[2]
Or
set(["."+ x.rsplit('.', 1)[-1] for x in a])
Or using pop()
set(["."+ x.rsplit('.', 1).pop() for x in a]))
Solution 3:[3]
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)
Solution 4:[4]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Riccardo Bucco |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | proPhet |
