我在使用python for udacity:
的challange中编写了这个函数example_input="John is connected to Bryant, Debra, Walter.\
John likes to play The Movie: The Game, The Legend of Corgi, Dinosaur Diner.\
Bryant is connected to Olive, Ollie, Freda, Mercedes.\
Bryant likes to play City Comptroller: The Fiscal Dilemma, Super Mushroom Man.\
Mercedes is connected to Walter, Robin, Bryant.\
Mercedes likes to play The Legend of Corgi, Pirates in Java Island, Seahorse Adventures.\
Olive is connected to John, Ollie.\
Olive likes to play The Legend of Corgi, Starfleet Commander.\
Debra is connected to Walter, Levi, Jennie, Robin.\
Debra likes to play Seven Schemers, Pirates in Java Island, Dwarves and Swords.\
Walter is connected to John, Levi, Bryant.\
Walter likes to play Seahorse Adventures, Ninja Hamsters, Super Mushroom Man.\
Levi is connected to Ollie, John, Walter.\
Levi likes to play The Legend of Corgi, Seven Schemers, City Comptroller: The Fiscal Dilemma.\
Ollie is connected to Mercedes, Freda, Bryant.\
Ollie likes to play Call of Arms, Dwarves and Swords, The Movie: The Game.\
Jennie is connected to Levi, John, Freda, Robin.\
Jennie likes to play Super Mushroom Man, Dinosaur Diner, Call of Arms.\
Robin is connected to Ollie.\
Robin likes to play Call of Arms, Dwarves and Swords.\
Freda is connected to Olive, John, Debra.\
Freda likes to play Starfleet Commander, Ninja Hamsters, Seahorse Adventures."def create_data_structure(string_input):
for x in string_input:
if not ((ord(x)>60 and ord(x)<90) or x=="." or (ord(x)>97 and ord(x)<122)):
string_input=string_input[:string_input.index(x)]+string_input[string_input.index(x):]
network={}
before=0
string_input2=string_input
while y < string_input.count('.')+1:
network[y]=string_input2(0:before)
string_input2=string_input2(:before-1)
before=string_input2.find('.')
return network,len(string_input),string_input
当我运行代码时,编辑器会出错 消息说切片不起作用。
Traceback (most recent call last):
File "vm_main.py", line 33, in <module>
import main
File "/tmp/vmuser_igvmlwmdgu/main.py", line 2, in <module>
import studentMain
File "/tmp/vmuser_igvmlwmdgu/studentMain.py", line 103
network[y]=string_input2(0:11)
^
SyntaxError: invalid syntax
有人可以告诉我出了什么问题吗?
答案 0 :(得分:3)
在Python中对字符串/ list / tuple进行切片的语法是[:]
而不是(:)
,即使用括号而不是括号。尝试:
string_input2[0:11]
例如:
>>> my_string = 'StackOverflow'
>>> my_string[5:9]
'Over'