Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding whether a string starts with one of a list's variable-length prefixes

Tags:

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?

like image 863
Kawu Avatar asked Sep 24 '11 15:09

Kawu


People also ask

How do you check if a string has a prefix?

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.

How do you check if a string starts with a certain letter python?

The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .

How do you check if a string starts with a substring in Golang?

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.

How do you check if a string is a certain length python?

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”.


2 Answers

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 
like image 61
dm03514 Avatar answered Oct 31 '22 12:10

dm03514


A bit hard to read, but this works:

name=name[len(filter(name.startswith,prefixes+[''])[0]):] 
like image 34
Vaughn Cato Avatar answered Oct 31 '22 11:10

Vaughn Cato