0

I am testing a set of web apis, using python, a language I am still in the process of learning. I am taking in a string, the name of a dealer, and chopping off the end after a random number of characters. I am then adding a character (wild card) to then end of the string. That modified string is then passed to an api that searches for the name of a dealer, and can include wild cards. I have the code below, but it seems long. Is there a cleaner looking, or more pythonic way of approaching this problem? Potentially a way to do this without converting from a string, to a list, back to a string?

split_name = list(name)     #turns name string into list
rand = random.randint(6,(len(split_name)-1))    #generates random number
split_name[rand:len(split_name)] = []       #breaks of end part of name list
srch_name = ''.join(split_name)     #stringifies list
#Send request
rqst = requests.get(name_srch %(key, (srch_name + '*'))) #this adds * and sends the request

Name is earlier defined in the script to be some string, such as "Dave and Bills equipment sales and service, INC" I should note I am using python 2.7

1 Answer 1

2

Yes, use slicing to pick a random number of characters from the string, no need to split it into a list first:

rand = random.randint(6, len(split_name) - 1)
search_name = name[rand:] + '*'
rqst = requests.get(name_srch % (key, search_name))

Strings are sequences too and support slicing directly without needing to turn it into a list first. You can omit the end-point, slicing defaults to the end of the string in that case.

Sign up to request clarification or add additional context in comments.

3 Comments

In response to your original answer: it should be noted that string.split() is around twice as fast as list(string).
@2rs2ts: but the .split() does something completely different.
Thanks Martijn, this is a better solution. At some point I have to search for partialwordpartialword. With the method you have shown that becomes much easier than my code (i won't paste here, it looks terrible), as its just 'search_name = name[:rand1] + "" + name[rand2:]' with the rands appropriately calculated. @2rs2ts, I had thought about using 'string.split()' but didn't see a need to only insert the wildcard between whole words. Out of curiosity, why would it be about twice as fast? Just because it's creating a smaller list?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.