首页 > 解决方案 > Python在字符串中查找波浪号

问题描述

我试图在字符串中找到“~”,但它返回 0。

有人可以帮忙吗?

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

标签: pythonstringfind

解决方案


find您一起寻找子字符串在字符串中的位置。0表示您的子字符串从 index 开始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 ~!)

您可以对字符串执行许多操作。


推荐阅读