我的任务是从字符串中创建一个列表。然后将所有元素从列表移动到另一个列表并再次将其转换为字符串。 这就是我所做的:
def string_list(sentence: str) -> str:
result = []
sentence = sentence.split(" ")
while sentence:
for i in range(len(sentence)):
tmp_var = sentence[i]
result.append(tmp_var)
sentence.remove(tmp_var)
return " ".join(result)
print(string_list("Hey, how's it going?"))
但我收到此错误消息:IndexError: list index out of range
提前致谢!
请您参考如下方法:
如果你愿意,你可以尝试列表理解:
string_1="Hey, how's it going?"
origional_list=[i for i in string_1]
string_to_list=[i for i in origional_list if i!=',' and i!="'" and i!=' ']
print("String to list : {}".format(string_to_list))
list_to_string=("".join(origional_list))
print("list to String : {}".format(list_to_string))
输出:
String to list : ['H', 'e', 'y', 'h', 'o', 'w', 's', 'i', 't', 'g', 'o', 'i', 'n', 'g', '?']
list to String : Hey, how's it going?
