【问题标题】:how do I take out index and not all of the char in a string?如何取出索引而不是字符串中的所有字符?
【发布时间】:2021-01-29 09:46:09
【问题描述】:

我想指示计算机,如果字符串“a”中的一个字符也是字符串“b”中的一个字符,则删除该字符(只是那个字符),但是下面的代码正在做的是删除所有一次从字符串中提取相同的字符。有什么帮助吗?

我尝试使用 a[I] 和 b[I] 来替换每个循环的索引,但是下面的代码需要完全更改,因为我不能再执行 'for I in a' 和 '如果我在 b' 中,因为我需要对 'i' 的整数引用。

例如a = "askhfidshf" b = "fhsdhfojej"

def permutation_checker(a,b):
    if a==b:
        print("a is a permutation of b")

    if a != b:
        while a and b:
            for i in a:
                if i in b:
                    new_a = a.replace(i,"")
                    print(new_a)
                    a = new_a
                    new_b = b.replace(i,"")
                    print(new_b)
                    b =new_b

                    if (a=="") and b == "":
                        print("a is a permutation of b")

【问题讨论】:

    标签: python for-loop if-statement indexing


    【解决方案1】:

    replace method 带有一个参数,该参数指定应替换的出现次数。默认情况下会全部替换。

    str.replace(old, new[, count])
    

    【讨论】:

      【解决方案2】:

      我认为字符串操作有点复杂,我建议将其转换为数组,因为您可以利用索引方法,并且您获取整数引用的挑战将得到解决。看看我想出的代码。

      def permutation_checker(a, b):
          array_a = [i for i in a] # converting the string to an array
          array_b = [i for i in b] # converting the string to an array
      
          for i in range(len(array_a )):
              if array_a[i] in array_b:
                  char_index = array_b.index(array_a[i]) # getting the first index of the value array_a[i] within array_b
                  array_b[char_index] = ''
      
          if array_b == [''] * len(b):
              print(f'{a} is a permutation of {b}')
      

      【讨论】:

      • 感谢分享。事实上,我使用数组做得更好,这是我的第一个想法,但我遇到了同样的整数问题。但我现在看到您的解决方案如何解决这个问题!谢谢
      猜你喜欢
      • 1970-01-01
      • 2022-01-20
      • 2019-10-10
      • 1970-01-01
      • 2013-03-13
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      相关资源
      最近更新 更多