[英]Python: How do I remove the formatting when joining items from a list into a string?
Good morning, all: 大家早上好:
I'm working on a small Python program which matches together small strings in order to make up fictional company names. 我正在研究一个小的Python程序,它将小字符串匹配起来以构成虚构的公司名称。 The name segments are stored in three lists, and a random string from each list is chosen each time a new name is requested. 名称段存储在三个列表中,每次请求新名称时,都会选择每个列表中的随机字符串。 For example, the program might pick "Eli", "rce" and "Softworks" from the three lists, which would give me "Elirce Softworks". 例如,程序可能从三个列表中选择“Eli”,“rce”和“Softworks”,这将给我“Elirce Softworks”。
seg1 = namesegs1[random.randint(0, seg1_length)]
seg2 = namesegs2[random.randint(0, seg2_length)]
seg3 = namesegs3[random.randint(0, seg3_length)]
new_name = "{0}{1} {2}".format(seg1, seg2, seg3)
However, the code actually returns ['Eli']['rce'] ['Softworks']. 但是,代码实际上返回['Eli'] ['rce'] ['Softworks']。 It makes sense, given that it's joining items from lists, but I don't see why these can't be removed in some way or another. 这是有意义的,因为它是从列表中加入项目,但我不明白为什么这些不能以某种方式被删除。
Here's one way I've made it work: 这是我使其成功的一种方式:
new_name = new_name.replace("'", "")
new_name = new_name.replace(",", "")
new_name = new_name.replace("[", "")
new_name = new_name.replace("]", "")
That gets rid of the formatting nicely, but it's less than satisfactory and it feels like I'm doing it wrong. 这很好地摆脱了格式化,但它不太令人满意,感觉我做错了。 Is there a better way to be going about this? 有没有更好的方法来解决这个问题?
Many thanks for your time. 非常感谢你的时间。
It looks like namesegs1
is a list of lists rather than a list of strings. 看起来namesegs1
是列表而不是字符串列表。
What do you get with the following? 你对以下内容有什么看法?
new_name = "{0}{1} {2}".format(seg1[0], seg2[0], seg3[0])
By the way, use random.choice(namesegs1)
to select a random item from your list, rather than that thing you've done with random.randint
. 顺便说一句,使用random.choice(namesegs1)
从列表中选择一个随机项,而不是你用random.randint
做的那个。
Are you familiar with Python string join functionality? 您熟悉Python字符串连接功能吗? For me it sounds like what you need. 对我来说,这听起来像你需要的。
http://docs.python.org/2/library/stdtypes.html#str.join http://docs.python.org/2/library/stdtypes.html#str.join
Suppose your logic with the randomizer generates an input list as: input_list = [['Eli'],['rce'],['Softworks']]
假设你的随机input_list = [['Eli'],['rce'],['Softworks']]
逻辑生成一个输入列表: input_list = [['Eli'],['rce'],['Softworks']]
the following code will give you what you need: 以下代码将为您提供所需内容:
input_list = [i[0] for i in input_list]
''.join(input_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.