[英]Python 2.7: Select specific character from string
I'm trying to figure out how to select a specific character from a string. 我试图找出如何从字符串中选择特定字符。 I know you can use the [0:0]
and [0:-0]
syntax etc... However I'm trying to do something different. 我知道你可以使用[0:0]
和[0:-0]
语法等...但是我正在尝试做一些不同的事情。
If a user enters "Hello, my name is [lol] bob [not[really]] john[son]"
or enters "[[[[]]][[][][]"
如果用户输入"Hello, my name is [lol] bob [not[really]] john[son]"
或输入"[[[[]]][[][][]"
I'm trying to count how many square brackets have been typed and either left or right. 我正在计算已经键入了多少个方括号,左或右。
Thanks a lot guys for the instant response, a lot of help! 非常感谢大家的即时回复,很多帮助!
You can use str.count
method if you only need to count them: 如果只需要计算它们,可以使用str.count
方法:
>>>s = "Hello, my name is [lol] bob [not[really]] john[son]"
>>>s.count('[') + s.count(']')
8
May be there have a better way, but it will do: 可能有更好的方法,但它会做:
input = 'Hello, my name is [lol] bob [not[really]] john[son]'
print len(re.findall("\[|\]", input))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.