解析字符串以查找elemen

2024-05-14 22:52:44 发布

您现在位置:Python中文网/ 问答频道 /正文

#!/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)

正在尝试实现一个函数,该函数在字符串中查找",并在找到它时打印"hw"。有什么问题吗


Tags: 函数inforreturnifbinusrdef
2条回答

list indices must be integers, not list.

我修改了您的代码,请尝试下面的代码:

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

或:

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)

或:

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

更新

其实比你想象的简单多了。首先split是一个内置函数。其次,for i in a检查字符串的每个字符a您不需要索引。请尝试以下操作:

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

如果还需要获取找到的字符的索引,可以执行以下操作:

s = "string\"\""
print([(i, "hw") for i, j in enumerate(s) if j == "\""])

相关问题 更多 >

    热门问题