查找字符串中第一个字符的索引
Find index of first of two characters in a string
给定以下字符串:
foo = "hello + there"
bar = "hello - there"
baz = "one + two - three"
fuz = "one - two + three"
是否有(相对)直接的方法来获取 +
或 -
第一个字符的索引?
foo.index_multiple('+-') # 6
bar.index_multiple('+-') # 6
baz.index_multiple('+-') # 4
fuz.index_multiple('+-') # 4
编辑:我不要求自定义代码(例如 Python 例程)——这相对简单,我可以自己完成。我只想知道是否有任何内置的用于此目的的东西,可能会或可能不会使用正则表达式。
您可以通过以下方式使用re.search()
:
import re
string = "test + Line"
match = re.search(r"[+-]", string)
if match:
print("Character + or - found at ", match.start())
else:
print("No + or - found")
给定以下字符串:
foo = "hello + there"
bar = "hello - there"
baz = "one + two - three"
fuz = "one - two + three"
是否有(相对)直接的方法来获取 +
或 -
第一个字符的索引?
foo.index_multiple('+-') # 6
bar.index_multiple('+-') # 6
baz.index_multiple('+-') # 4
fuz.index_multiple('+-') # 4
编辑:我不要求自定义代码(例如 Python 例程)——这相对简单,我可以自己完成。我只想知道是否有任何内置的用于此目的的东西,可能会或可能不会使用正则表达式。
您可以通过以下方式使用re.search()
:
import re
string = "test + Line"
match = re.search(r"[+-]", string)
if match:
print("Character + or - found at ", match.start())
else:
print("No + or - found")