For Python 3.9+:
text.removeprefix(prefix)
For older versions, the following provides the same behavior:
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text
Answer from Elazar on Stack OverflowFor Python 3.9+:
text.removeprefix(prefix)
For older versions, the following provides the same behavior:
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text
Short and sweet:
def remove_prefix(text, prefix):
return text[text.startswith(prefix) and len(prefix):]
How to remove a string from a list that startswith prefix in python - Stack Overflow
python - Remove a prefix if matches an entry on a list - Stack Overflow
regex - How to remove the prefix from each element of python list? - Stack Overflow
python - What is the best way to get rid of common substring prefix in Python3? - Stack Overflow
try:
strList = map( str, objList)
strList = map( lambda x: x.replace( 'Volume:', ''), strList)
You could reduce @Marek code to one line:
strList = list(map(lambda x: str(x).replace('Volume:', ''), strList))
or just use list comprehension:
new_list = [str(i).replace( 'Volume:', '') for i in your_list]
Since Python 3.9 you can use removeprefix() function what will simplify your code even more:
new_list = [str(i).removeprefix('Volume:') for i in your_list]
More info about removeprefix(): PEP 616
You can create a new list that contains all the words that do not start with one of your prefixes:
newlist = [x for x in list if not x.startswith(prefixes)]
The reason your code does not work is that the startswith method returns a boolean, and you're asking to remove that boolean from your list (but your list contains strings, not booleans).
Note that it is usually not a good idea to name a variable list, since this is already the name of the predefined list type.
Greg's solution is definitely more Pythonic, but in your original code, you perhaps meant something like this. Observe that we make a copy (using list[:] syntax) and iterate over the copy, because you should not modify a list while iterating over it.
prefixes = ('hello', 'bye')
list = ['hi', 'helloyou', 'holla', 'byeyou', 'hellooooo']
for word in list[:]:
if word.startswith(prefixes):
list.remove(word)
print list
If you only want to search for whole words they will be terminated by a space character. I suggest you append it to the prefix:
prefixes = [u'path', u'folder', u'directory', u'd']
mystrings = [u'path common path and directory', u'directory common path and directory', u'directory folder distinct and directory folder', u'distinct and directory folder', u'd fixable directory or folder']
for s in mystrings:
for prefix in prefixes:
if s.startswith(prefix+" "):
print s[len(prefix)+1:]
Demo
>>>
common path and directory
common path and directory
folder distinct and directory folder
fixable directory or folder
I would split by " " to get the first word, and remove it if it's in the prefix list.
firstWord=s1.split(" ")[0]
if firstWord in prefixes:
s1=" ".join(s1.split(" ")[1:])
You can also split on all whitespace with split()
Here's one approach using re.sub:
import re
l = ['[ 1.1 ] 1. a electronic bill presentment system.','[ 1.2 ] a network.']
[re.sub(r'\[\s*\d+\.*\d*\s*\]\s+(?:\d+\.\s*)?', '', s) for s in l]
# ['a electronic bill presentment system.', 'a network.']
See demo
Testing with a larger list of strings:
l = ['[ 1.1 ] 1. a electronic bill presentment system.',\
'[ 1.2 ] a network.',\
'[ 1.3 ] a plurality of first stations, each associated with a respective one of a plurality of users and operable to transmit first requests for bills of its associated user via the network.',\
'[ 1.5 ] a plurality of second network stations, each associated with a respective one of a plurality of billers, configured to receive the transmitted second requests for bills and to transmit, responsive thereto, the requested bills of the associated user via the network.',\
'[ 1.6 ] wherein the bill availability information for the associated user identifies those of the plurality of billers having a bill available for that user without identifying an amount of the bill of each of the identified billers for the associated user.',\
'[ 2.1 ] 2. a method for presenting electronic bills.']
[re.sub(r'\[\s*\d+\.*\d*\s*\]\s+(?:\d+\.\s*)?', '', s) for s in l]
['a electronic bill presentment system.',
'a network.',
'a plurality of first stations, each associated with a respective one of a plurality of users and operable to transmit first requests for bills of its associated user via the network.',
'a plurality of second network stations, each associated with a respective one of a plurality of billers, configured to receive the transmitted second requests for bills and to transmit, responsive thereto, the requested bills of the associated user via the network.',
'wherein the bill availability information for the associated user identifies those of the plurality of billers having a bill available for that user without identifying an amount of the bill of each of the identified billers for the associated user.',
'a method for presenting electronic bills.']
You should regular expression to substitute the pattern with an empty string
>>> re.sub(r'\[\s?\d\.\d\s?]\s?(\d(\.\s)?)?', '', '[ 1.1 ] 1. a electronic bill presentment system.')
'a electronic bill presentment system.'
I would compute the common prefix of all strings using os.path.commonprefix, then slice the strings to remove that prefix (this function is in os.path module but doesn't check path separators, it's useable in a generic context):
import os
p = ["<common-part>-<some-text-a>", "<common-part>-<random-text-b>"]
commonprefix = os.path.commonprefix(p)
new_p = [x[len(commonprefix):] for x in p]
print(new_p)
result (since commonprefix is ""<common-part>-<"):
['some-text-a>', 'random-text-b>']
notes:
- this method allows a full dynamic prefix, not known in advance. With reversing the strings, it's also possible to remove the common suffix.
- it's better to use
lento slice the result instead ofstr.replace(): it's faster, and it only removes the start of the string, and safe since we know that all strings start by this prefix.
MyList = ["xxx-56", "xxx-57", "xxx-58"]
MyList = [x[len(prefix):] for x in MyList] # for each x in the list,
# this function will return x[len(prefix):]
# which is the string x minus the length of the prefix string
print(MyList)
---> ['56', '57', '58']
Another approach which will work for all scenarios:
import re
data = ['clean_be',
'clean_be_al',
'clean_fish_po',
'clean_po', 'clean_a', 'clean_clean', 'clean_clean_1']
for item in data:
item = re.sub('^clean_', '', item)
print (item)
Output:
be
be_al
fish_po
po
a
clean
clean_1
Here is a possible solution that works with any prefix:
prefix = 'clean_'
result = [s[len(prefix):] if s.startswith(prefix) else s for s in lst]