【问题标题】:Using regular expression to count the number of spaces at the beginning of a string [duplicate]使用正则表达式计算字符串开头的空格数[重复]
【发布时间】:2019-01-11 21:41:54
【问题描述】:

如何使用正则表达式计算字符串开头的空格数。例如:

string = ' area border router'

count_space 变量将返回值 1,因为字符串开头有 1 个空格。如果我的字符串是:

string = '  router ospf 1'

count_space 变量将返回值 2,因为字符串开头有 2 个空格。等等……

我认为表达式会类似于 RE = '^\s' ?但不确定如何制定。

【问题讨论】:

标签: python string whitespace space


【解决方案1】:

你不需要正则表达式,你可以这样做:

s = ' area border router'
print(len(s)-len(s.lstrip()))

输出:

1

【讨论】:

  • 我不能接受..我没有足够的选票...您的解决方案绝对有效!非常感谢..您的回答比我发布链接的速度更快..
  • 当字符串还包含除空格之外的其他空白字符时,这不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
相关资源
最近更新 更多