我在Python中尝试计算字符串中的子字符串。
string = "aaaaahehabdha"
x = string.index("he") #5
y = string.rindex("ha") #11
z = y - x + 2 #lenght of substring 11 - 5 + 2 = 8
a = []
a.append(string.count("he", x, z)) #1
a.append(string.count("ha", x, z)) #count only once"ha" but in substring I have 2 x "ha"
print(a) # [1,1]
为什么string.count(“ha”,x,z)只计算一次“ha”? 提前谢谢。
答案 0 :(得分:0)
.count
的第三个参数不是长度,而是非包含性结束索引。计算正确的终点:
z = y + 2
示例,包括评论示例,计算从he
到ha
的正确子字符串:
string = "aaaaahehabdha"
x = string.index("he")
y = string.rindex("ha")
z = y + 2
print('substring:',string[x:z])
string = "aaaaahehabdhaaaaaaaaaaa"
x = string.index("he")
y = string.rindex("ha")
z = y + 2
print('substring:',string[x:z])
输出:
substring: hehabdha
substring: hehabdha
答案 1 :(得分:0)
如果您只想计算子字符串中“ha”的数量,您只需使用string.count("ha")
,它将返回2.
答案 2 :(得分:0)
您的参数public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstname', TextType::class, ['attr' => ['class' => 'form-control']])
->add('secondname', TextType::class, ['attr' => ['class' => 'form-control']])
->add('email', EmailType::class, ['attr' => ['class' => 'form-control']])
->add('password', PasswordType::class, ['attr' => ['class' => 'form-control']])
->add('password_confirmation', PasswordType::class, [
'label' => 'Confirm Password',
'attr' => ['class' => 'form-control'],
'mapped' =>false
])
->add('Register', SubmitType::class, ['attr' => ['class' => 'btn btn-primary']]);
}
和x
是在字符串中搜索位置的起始和结束索引,但起始索引始终是包含的,而结束索引始终是非包含的。您在z
之后存储了要搜索的起始索引之后的长度,当您确实应该调用时
z