简体   繁体   English

python是否有更好的方法来拆分字符串而不是转换为列表?

[英]Does python have a better way to split a string than converting to a list?

I am testing a set of web apis, using python, a language I am still in the process of learning. 我正在测试一组web apis,使用python,这是一种我仍在学习的语言。 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. 然后将该修改后的字符串传递给api,该API搜索经销商的名称,并且可以包括通配符。 I have the code below, but it seems long. 我有下面的代码,但似乎很长。 Is there a cleaner looking, or more pythonic way of approaching this problem? 是否有更清洁的外观或更多的pythonic方式来解决这个问题? 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 名称在脚本中早先定义为某些字符串,例如“Dave and Bills设备销售和服务,INC”我应该注意我使用的是python 2.7

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. 在这种情况下,您可以省略端点,将默认值切换到字符串的末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM