[英]check whether a string contains a character in python
I am trying to compare and see if a particular character exists in the string, but when i try to access the character which is in another string, its throws an error 'argument of type 'int' is not iterable'. 我正在尝试比较并查看字符串中是否存在特定字符,但是当我尝试访问另一个字符串中的字符时,它会抛出错误“类型为'int'的参数不可迭代”。 How do i access the character from a string without causing the error? 如何在不引起错误的情况下从字符串访问字符?
def lengthOfLongestSubstring(self, s: str) -> int:
longStrLen = 0
totalStrLen = len(s)
holderString = ""
holderString += s[0]
longStrLen = 0
for i in range(1,totalStrLen-1):
if s[i] not in holderString:
holderString += s[i]
else:
if longStrLen < len(holderString):
longStrLen = len(holderString)
holderString = 0
return longStrLen
TypeError: argument of type 'int' is not iterable at Line
if s[i] not in holderString:
Your problem is on this line: 您的问题在这条线上:
holderString = 0
You reassigned the holderString
variable to the integer 0. While strings can be iterated over, integers cannot. 您holderString
变量重新分配为整数0。虽然可以迭代字符串,但不能整数。 You attempt to iterate over the new integer on this line: 您尝试遍历此行上的新整数:
if s[i] not in holderString:
which causes the error. 导致错误。
There is a much better way to approach a function that returns the first repeated character though. 有一种更好的方法来处理返回第一个重复字符的函数。 Simply use the index()
method: 只需使用index()
方法:
def findChar(char, string):
for c in string:
if c == char:
return string.index(c)
It appears you only need to count unique characters until you find the first duplicate. 看来,您只需要计算唯一字符,直到找到第一个重复字符。 You can do that with a set. 您可以通过设置来做到这一点。
def longest_substring(s: str) -> int:
seen = set()
for c in s:
if c in seen:
break
seen.add(c)
return len(seen)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.