简体   繁体   English

使用 python 中的 2 个变量对字符串进行切片的方法

[英]Way to slice a string using 2 variable in python

I m new to programming and came across a question If I have a string where I have 2 variables indexed.. and need the value from the middle.我是编程新手,遇到了一个问题,如果我有一个字符串,其中我有 2 个变量索引.. 并且需要中间的值。

for example, my string is HeyEveryoneImtryingtolearnpythonandihavequestion where I have variables例如,我的字符串是HeyEveryoneImtryingtolearnpythonandihavequestion我有变量

V1 = 'Imtrying'
V2 = 'andihave'

what can I do to get the "learnpython" substring?我该怎么做才能获得“learnpython”substring? or is it not valid?还是无效?

You can use index and slicing:您可以使用index和切片:

s = 'HeyEveryoneImtryingtolearnpythonandihavequestion'

v1 = 'Imtrying'
v2 = 'andihave'

start = s.index(v1) + len(v1)
end = s.index(v2, start)

output = s[start:end]
print(output) # tolearnpython

You can also use regex:您还可以使用正则表达式:

import re

s = "HeyEveryoneImtryingtolearnpythonandihavequestion"
V1 = 'Imtryingto'
V2 = 'andihave'

a = re.search(f"{re.escape(V1)}(.*?){re.escape(V2)}", s).group(1) # 'learnpython'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM