我们如何找到字符串中所有长度为n的子字符串?假设字符串为'Jonathan'
。那么所有的length-3子字符串都是:
'Jon','ona',...'han'
我想为此使用正则表达式。我尝试使用re.findall('...','Jonathan)
,但没有完全满足我的需求。
答案 0 :(得分:1)
如果您真的想使用正则表达式执行任务,那么我建议您使用此-
import re
print(re.findall(r'(?=(\w\w\w))', 'Jonathan'))
您可以根据所需的长度-\w
个子字符串来增加或减少n
的数量。
输出-
['Jon', 'ona', 'nat', 'ath', 'tha', 'han']
另一个例子-
print(re.findall(r'(?=(\w\w\w\w))', 'Jonathan'))
输出-
['Jona', 'onat', 'nath', 'atha', 'than']
希望这会有所帮助!
在您最近发表评论之后,这可能会起作用-
示例1-
import re
s = "amam"
m = re.compile(".m.")
h = m.findall(s)
print(h)
输出-
['ama']
示例2-
import re
s = "Jonathan"
m = re.compile(".o.")
h = m.findall(s)
print(h)
输出-
['Jon']
示例3-
import re
s = "Jonathanona"
m = re.compile(".o.")
h = m.findall(s)
print(h)
输出-
['Jon', 'non']
希望这会有所帮助!
答案 1 :(得分:0)
您不需要正则表达式。使用zip
:
name = 'Jonathan'
print([x + y + z for x, y, z in zip(name, name[1:], name[2:])])
# ['Jon', 'ona', 'nat', 'ath', 'tha', 'han']