【问题标题】:string.split() is not working when passing it as argument to another function将 string.split() 作为参数传递给另一个函数时不起作用
【发布时间】:2020-11-24 04:06:27
【问题描述】:

我的代码:

testcases=int(input())
position=1
seconds=0
dictionary={1:".,;?", 2:"abc", 3:"def", 4:"ghi", 5:"jkl", 6:"mno", 
               7:"pqrs", 8:"tuv", 9:"wxyz", 0:" " }


def calculation(array,position):
    s=0
    print(array) # Here array shows ['1 2']
    for string in array:
        for character in string:
            if character in str(dictionary.keys()):
                if position==int(character):
                    s+=1
                else:
                    position=int(character)
                    s+=2
                print(position)
                #break
       
     return s

for test in range(testcases):
    string=input()
    if string.isspace()==False:
        seconds=calculation([string],position)
    else:
        seconds=calculation(string.split(),position) #Suppose my string="1 2"

假设我将"1 2" 作为输入,然后当我在函数calculation() 中打印字符串时,字符串显示为['1 2'] 而不是['1', '2']。为什么会这样?

【问题讨论】:

    标签: python string split


    【解决方案1】:

    这里[string] 将形成唯一元素string 的列表。如果 .isspace() 是 True ,也许你必须打电话:

    if string.isspace():
        seconds=calculation([string],position)
    else:
        seconds=calculation(string.split(),position)
    

    【讨论】:

    • 但我希望字符串被拆分,只有在有空格的情况下。
    • 您是否阅读了文档中 isspace 的定义?如果字符串中的所有字符都是空白字符,isspace 返回 True。
    • 顺便说一句,您甚至不需要 if...else 块。试试print('1'.split())print('1 2 3'.split()) 看看为什么。
    猜你喜欢
    • 2015-11-30
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    相关资源
    最近更新 更多