'I want to remove the first ( ) and it´s unkown content every time i loop
I tried the next code but it did not work:
info = ["Mark(Sat)", "James(Sun)", "Robert(Sun)", "John(Fri)"]
for x in info:
info.remove(info[info.find("("):info.find(")")])
print(x)
Consider that i do not know which content will be inside the ( )
I have to use loop because i do not want o remove all ( ) and it´s content at once.
SO i want to remove the first ( ) and it´s content every time i loop.
Solution 1:[1]
info = ["Mark(Sat)", "James(Sun)", "Robert(Sun)", "John(Fri)"]
new_lst = [a[:a.index('(')] for a in info]
print(new_lst)
OUTPUT
['Mark', 'James', 'Robert', 'John']
To not get any error if '(' not in list element.
info = ["Mark(Sat)", "James(Sun)", "RobertSun", "John(Fri)"]
new_lst = [a[:a.index('(')] if '(' in a else a for a in info]
print(new_lst)
OUTPUT
['Mark', 'James', 'RobertSun', 'John']
OR if you only want to remove text if (and ) both are present in the string then use this one.
Below Code return only delete text between ().
If string is 'Mark (sat) Steve' this will return 'Mark Steve'
info = ["Mark(Sat) Steve", "James(Sun) ", "RobertSun", "John(Fri)"]
new_lst = [a[:a.index('(')] + a[a.index(')')+1:] if '(' in a and ')' in a else a for a in info ]
print(new_lst)
OUTPUT
['Mark Steve', 'James ', 'RobertSun', 'John']
USING re module
import re
info = ["Mark(Sat)", "James(Sun)", "Robert(Sun)", "John(Fri)"]
new_lst = [re.sub(r'\(.+\)','',a) for a in info]
print(new_lst)
OUTPUT
['Mark', 'James', 'Robert', 'John']
Solution 2:[2]
Use str.split and take the first part, that works for string with and without the parenthesis
info = ["Mark(Sat)", "James(Sun)", "Robert(Sun)", "John(Fri)", "test"]
result = [name.split("(")[0] for name in info]
print(result) # ['Mark', 'James', 'Robert', 'John', 'test']
Solution 3:[3]
If you want to process each string in a loop and you want something that will implicitly account for unexpected data formats, then using RE might be a good option.
import re
info = ["Mark(Sat)", "James(Sun)", "Robert(Sun)", "John(Fri)"]
for e in info:
print(re.sub('\(.*\)', '', e))
Output:
Mark
James
Robert
John
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 | |
| Solution 2 | azro |
| Solution 3 | Albert Winestein |
