简体   繁体   English

Python Split Output在方括号中

[英]Python Split Outputting in square brackets

I have code that looks like this: 我有看起来像这样的代码:

import re
activity = "Basketball - Girls 9th"
activity = re.sub(r'\s', ' ', activity).split('-')
activity = str(activity [1:2]) + str(activity [0:1])
print("".join(activity))

I want the output to look like Girl's 9th Basketball , but the current output when printed is [' Girls 9th']['Basketball '] I want to get rid of the square brackets. 我希望输出看起来像Girl's 9th Basketball ,但打印时的当前输出是[' Girls 9th']['Basketball ']我想摆脱方括号。 I know I can simply trim it, but I would rather know how to do it right. 我知道我可以简单地修剪它,但是我宁愿知道如何正确地修剪它。

You are stringyfying the lists which is the same as using print(someList) - it is the representation of a list wich puts the [] around it. 您正在用清单print(someList) ,这与使用print(someList) -它是将[] print(someList)起来的清单的表示形式。

import re
activity = "Basketball - Girls 9th"
activity = re.sub(r'\s', ' ', activity).split('-')
activity =  activity [1:2]  + [" "] +  activity [0:1] # reorders and reassignes list

print("".join(activity))

You could consider adding a step: 您可以考虑添加一个步骤:

# remove empty list items and remove trailing/leading strings
cleaned = [x.strip() for x in activity if x.strip() != ""]

print(" ".join(cleaned)) # put a space between each list item

This just resorts the lists and adds the needed space item in between so you output fits. 这只是对列表进行排序,并在它们之间添加所需的空格,因此您可以输出拟合。

You're almost there. 你快到了。 When you use .join on a list it creates a string so you can omit that step. list上使用.join ,它将创建一个string因此您可以省略该步骤。

import re
activity = "Basketball - Girls 9th"
activity = re.sub(r'\s', ' ', activity).split('-')
activity = activity[1:2] + activity[0:1]
print(" ".join(activity))

您可以在一行中解决它:

new_activity = ' '.join(activity.split(' - ')[::-1])

You can try something like this: 您可以尝试如下操作:

import re
activity = "Basketball - Girls 9th"
activity = re.sub(r'\s', ' ', activity).split('-')
activity = str(activity [1:2][0]).strip() + ' ' + str(activity [0:1][0])
print(activity)

output: 输出:

Girls 9th Basketball 

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

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