Python在字符串中找到代字号

时间:2018-08-15 10:10:14

标签: python string find

我正在尝试在字符串中找到“〜”,但它返回0。

有人可以在这里帮忙吗?

tt = "~"
tt.find("~")
Out[393]: 0

4 个答案:

答案 0 :(得分:3)

使用find,您正在查找子字符串在字符串中的位置。 0表示您的子字符串从索引0开始。
如果只想检查字符串是否包含子字符串,则可以使用:

~在字符串开头:

my_string = "~ This is a test"
print("~" in my_string) # True
print(my_string.find("~")) # 0 (index)

这意味着~可以在字符串的索引0中找到。由于python从0开始计算索引,因此意味着~是第一个字符(这是真的!)

~在字符串中间:

my_string = "This is a ~ test"
print("~" in my_string) # True
print(my_string.find("~")) # 10 (index)

这意味着~可以在字符串的索引10中找到。这意味着~是第11个字符(是真的!)

~不在字符串中:

my_string = "This is a test"
print("~" in my_string) # False
print(my_string.find("~")) # -1 (false)

字符串中有两个~

my_string = "~This is a ~test"
print("~" in my_string) # True
print(my_string.find("~")) # 0 (only the index of the FIRST ~!)

您可以对字符串执行many operations

答案 1 :(得分:1)

0的意思是“在位置0找到”。

-1的意思是“未找到”。

一切都很好。

答案 2 :(得分:1)

该功能正常运行。 Python的索引从0(不是1)开始工作。输出0表示在第0个索引处找到“〜”。如果find找不到字符,则输出-1。

答案 3 :(得分:0)

str具有方法find,该方法查找字符串中是否存在子字符串。它返回找到的子字符串的位置。如果找不到子字符串,则返回-1

在示例tt = "~"中,波浪号符号位于位置0。运行命令tt.find("~")时,波浪号位于位置0,并返回该值。

检查此示例以更好地理解:

tt = "The tilde ~ symbol"
tt.find("~")
# 10

方法find接受一个位置参数(要查找的子字符串)和两个可选的关键字参数begend-分别是开始索引和结束索引。

想象一下这种情况:

tt = "~ where is the ~ symbol ~"
tt.find("~", 1, len(tt)-1)
# 15

此处搜索中省略了第一个和最后一个字符。