假设我有一条字符串:
'0123456abcde78sdfnwjeabcde8923kasjsducuabcded999'如何将子字符串'abcde'两个字符移到生成的右侧:
'012345678abcdesdfnwje89abcde23kasjsducud9abcde99'所以这个:
s = '0123456abcde78'
t = 'abcde'
n = 2 # (right shift)
Function(s, t, n) 应给予:
'012345678abcde'可以安全忽略的边缘情况:
'abcde1')更少的字符'abcdeabcde123')的连续出现发布于 2022-02-16 12:25:06
我将使用replace - re.sub的正则表达式。
import re
s = "0123456abcde78sdfnwjeabcde8923kasjsducuabcded999"
t = 'abcde'
n = 2
print(re.sub(rf"({t})(.{{{n}}})", r"\2\1", s))给予:
012345678abcdesdfnwje89abcde23kasjsducud9abcde99解释:
- `(` - First matching group:
- `{t}` - replaces `t` using f-strings - literally match the full substring.- `)` - End first group
- `(` - Second matching group:
- `.` - any character
- `{{` - escaped curly braces in f-string - to denote number of repetitions.
- `{n}` - f-string replacement of `n` - the number of repetitions.
- `}}` - escaped closing braces.- `)` - End second group- Simply replace the order of the above groups.要执行左移,只需更改组的顺序(即,首先匹配任何n字符,然后匹配t):
re.sub(rf"(.{{{n}}})({t})", r"\2\1", s)发布于 2022-02-16 12:30:35
根据要查找的字符串的索引位置创建一个新字符串。以下几行中的一些内容:
s = '0123456abcde78'
t = 'abcde'
n = 2 # (right shift)
tmp = s.index(t)
new_s = s[:tmp] + s[tmp+len(t):tmp+len(t)+n] + t + s[tmp+len(t)+n:]发布于 2022-02-16 12:30:42
Python字符串是不可变的,因此您必须从以下位置创建一个新字符串:
t在s中索引的开始n字符从t结尾开始(所以在`s.index(t) + len(t))tn字符开头的字符串结束,超过t的末尾。在Python中可以是:
def function(s, t, n):
ix = s.index(t)
length = len(t)
return s[:ix]+ s[ix + length: ix + length + n] + t + s[ix + length + n:]根据您的要求省略错误和角案例处理.
https://stackoverflow.com/questions/71141719
复制相似问题