-1
#!/usr/bin/python

def split(x):
    return [char for char in x]
def func(x):
    a = []
    a.append(split(x))
    for i in a:
        if a[i]== "\"":
            print ("hw")
str = "string\""
print (str)
func(str)

Trying to implement a function which finds " in a string and prints "hw" when finds it. What could be the problem?

Chüngel
  • 375
  • 4
  • 19
ccvhd
  • 202
  • 3
  • 10

2 Answers2

1

list indices must be integers, not list.

I modify your code, so, try code below:

def split(x):
    return [char for char in x]
def func(x):
    a = split(x)  # notice this line
    for i in range(len(a)):
        if a[i]== "\"":
            print ("hw")
str1 = "string\""
print (str1)
func(str1)

@See this Ouput Demo

Or:

def split(x):
    return [char for char in x]
def func(x):
    a = split(x)
    for i in a:
        if i == "\"":
            print ("hw")
str1 = "string\""
print (str1)
func(str1)

Or:

str1 = "string\""
test = ["hw" for i in str1 if i == '"']
print(test[0])
Siro
  • 76
  • 5
0

UPDATE

Actually it is much simpler than you think. First of all split is a built-in function. Secondly the for i in a checks every character of string a you do not need an index. Try the following:

s = "string\""
print("hw" if "\"" in s else None)

if you need to also get the indexes of the found characters you can do this:

s = "string\"\""
print([(i, "hw") for i, j in enumerate(s) if j == "\""])
Community
  • 1
  • 1
Kostas Charitidis
  • 2,991
  • 1
  • 12
  • 23