使用 Python 中的计数 在结果中添加一个字符?

Using the count in Python Add a Character in the result?

谁能给我解释一下:-

假设我有这个字符串变量

pcalpha = 'abcdefghijklmnopqrstuvwxyz'

编写这段代码 print(len(pcalpha)) 将导致 int 的输出等于 26 从我的理解是字符串中有 26 个字符。

写这段代码print(pcalpha.count(""))也应该根据下面的逻辑给出相同的结果,但不是。谁能告诉我为什么显示 27?

直觉上每个字母后有一个"",第一个字母前有一个。所以如果你有 26 个字母,那就意味着你有 26 "" 加上开头的那个 26 + 1 = 27。举个例子,让我们用“-”替换“”:

pcalpha = 'abcdefghijklmnopqrstuvwxyz'
print(pcalpha.replace("", "-"))

输出

-a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z-

进一步

  1. 如@RandomDavis 所述,有关实现细节,请参阅 this.
  2. Replacing the empty strings in a string