python - Python在字符串中查找波浪号
问题描述
我试图在字符串中找到“~”,但它返回 0。
有人可以帮忙吗?
tt = "~"
tt.find("~")
Out[393]: 0
解决方案
与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 ~!)
您可以对字符串执行许多操作。
推荐阅读
- python - 满足条件后如何停止python程序(在jupyter笔记本中)
- makefile - Variable expansion in target dependencies
- neo4j - Setting a property key for a node based on another node in a relationship
- haskell - 这种类型的孔怎么塞?
- elasticsearch - Kibana error on startup (incompatible nodes)
- javascript - 检查函数值而不是返回值时显示警告
- python - Importing modules that import other modules from other directories in Python 3.6
- reactjs - React 开发工具空白组件
- git - 创建新分支
- r - 如何使用具有匹配变量的不同长度的两个不同数据帧减去一个值