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.
CodePudding user response:
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']
CodePudding user response:
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']
CodePudding user response:
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