I need to find out whether a name starts with any of a list's prefixes and then remove it, like:
if name[:2] in ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"]: name = name[2:]
The above only works for list prefixes with a length of two. I need the same functionality for variable-length prefixes.
How is it done efficiently (little code and good performance)?
A for loop iterating over each prefix and then checking name.startswith(prefix)
to finally slice the name according to the length of the prefix works, but it's a lot of code, probably inefficient, and "non-Pythonic".
Does anybody have a nice solution?
To check if a String str starts with a specific prefix string prefix in Java, use String. startsWith() method. Call startsWith() method on the string str and pass the prefix string prefix as argument. If str starts with the prefix string prefix , then startsWith() method returns true.
The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .
In Golang strings, you can check whether the string begins with the specified prefix or not with the help of HasPrefix() function. This function returns true if the given string starts with the specified prefix and return false if the given string does not start with the specified prefix.
To calculate the length of a string in Python, you can use the built-in len() method. It takes a string as a parameter and returns an integer as the length of that string. For example len(“educative”) will return 9 because there are 9 characters in “educative”.
str.startswith(prefix[, start[, end]])¶
Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.
$ ipython Python 3.5.2 (default, Nov 23 2017, 16:37:01) Type 'copyright', 'credits' or 'license' for more information IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: prefixes = ("i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_") In [2]: 'test'.startswith(prefixes) Out[2]: False In [3]: 'i_'.startswith(prefixes) Out[3]: True In [4]: 'd_a'.startswith(prefixes) Out[4]: True
A bit hard to read, but this works:
name=name[len(filter(name.startswith,prefixes+[''])[0]):]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With