我想知道A != ""在这段代码中做了什么。
def mysplit(strng):
A = ""
B = []
for i in strng:
if i != " ":
A += i
elif A != "":
B.append(A)
A = ""
# Append last word
if A != "":
B.append(A)
return(B)这是我为一个uni项目找到的代码,但这段代码对我来说没有意义,不是空的吗?除了空格,你怎么能在你的文本中得到一个空字符?
还有,字符串有位置吗?
发布于 2022-02-13 06:20:37
解释:
A中,直到到达一个空格为止,当这种情况发生时,它会将A的内容作为一个列表转储到B中,这将是一个完整的单词,然后将A重置为'',这样它将继续逐字符读取下一个单词的字符。B将将字符串中的每个单词作为列表中的项包含,并返回.。
print('Hello World'[0:5])将返回的Hello:
代码:
def mysplit(strng):
A = ""
B = []
for i in strng: #Loop through each char in string
if i != " ": #if char is not a space
A += i #add character to A
elif A != "": #if A is not empty
B.append(A) #add whatever is in A to B as a list (full word)
A = "" #resets A to be empty
if A != "": #if A is empty
B.append(A)
return B #return is a statement, so it doesn't require parenthesis.发布于 2022-02-13 06:22:16
是的,字符串的索引从0到n-1,就像字符串中的索引一样。例:A = "abcd", print(a[2]) //output: "c"
对于您的代码,i遍历输入字符串中的每个元素,如果i不是“空格”,则将其附加到A。当它是“空格”时,A被附加到B列表中,A被清除,以便得到下一个单词。对于最后一个词,由于最后没有空格,所以字符串A不会被附加到B列表中,因此它是在For循环之外单独完成的。
https://stackoverflow.com/questions/71098303
复制相似问题