Python 在第一次出现字符之前插入字符串

Python 在第一次出现字符之前插入字符串,python,Python,所以基本上我有这个字符串\uuuuu int64\uuu fastcall(IOService*\uu隐藏了这个),我需要在\uu fastcall(这可以是任何东西)和(IOService…之间插入一个单词,例如\uu int64\uu fastcall LmaoThisWorks(IOService*\uu隐藏此); 我曾考虑过拆分字符串,但这似乎有点过分。我希望有一种更简单、更简短的方法: type_declaration_fun = GetType(fun_addr) # Sample:

所以基本上我有这个字符串
\uuuuu int64\uuu fastcall(IOService*\uu隐藏了这个),我需要在
\uu fastcall
(这可以是任何东西)和
(IOService…
之间插入一个单词,例如
\uu int64\uu fastcall LmaoThisWorks(IOService*\uu隐藏此);

我曾考虑过拆分字符串,但这似乎有点过分。我希望有一种更简单、更简短的方法:

type_declaration_fun = GetType(fun_addr) # Sample: '__int64 __fastcall(IOService *__hidden this)'
if type_declaration_fun:
    print(type_declaration_fun)
    type_declaration_fun = type_declaration_fun.split(' ')
    first_bit = ''
    others = ''
    funky_list = type_declaration_fun[1].split('(')
    for x in range(0, (len(funky_list))):
        if x == 0:
            first_bit = funky_list[0]
        else:
            others = others + funky_list[x]

    type_declaration_fun = type_declaration_fun[0] + ' ' + funky_list[0] + ' ' + final_addr_name + others
    type_declaration_fun = type_declaration_fun + ";"
    print(type_declaration_fun)
代码不仅是垃圾,而且不太有效。下面是一个示例输出:

void *__fastcall(void *objToFree)
void *__fastcall IOFree_stub_IONetworkingFamilyvoid;
我怎样才能让它工作起来更干净


请注意,可能会有嵌套的括号和其他奇怪的东西,因此您需要确保在第一个括号之前添加名称。

一旦找到需要插入的字符的索引,就可以使用拼接创建新字符串

    string = 'abcdefg'
    string_to_insert = '123'
    insert_before_char = 'c'
    for i in range(len(string)):
        if string[i] == insert_before_char:
            string = string[:i] + string_to_insert + string[i:]
            break
那么这个呢:

s = "__int64__fastcall(IOService *__hidden this);"
t = s.split("__fastcall",1)[0]+"anystring"+s.split("__fastcall",1)[1]
我得到:

__int64__fastcallanystring(IOService *__hidden this);
我希望这是你想要的。如果不是,请评论

   x='high speed'
    z='new text' 
    y = x.index('speed')
    x =x[:y] + z +x[y:]
print(x) 
>>> high new textspeed
这是一个简单的例子,请注意y inclusuve在新字符串之后


请注意,您正在更改原始字符串,或者只声明一个新字符串。

使用
regex

In [1]: import re

        pattern = r'(?=\()'
        string = '__int64 __fastcall(IOService *__hidden this);'
        re.sub(pattern, 'pizza', string)

Out[1]: '__int64 __fastcallpizza(IOService *__hidden this);'

模式是与第一次出现的
匹配的正向前瞻(

您可以使用方法
replace()

可能重复的
s = 'ABCDEF'
ins = '$'
before = 'DE'
new_s = s.replace(before, ins + before, 1)

print(new_s)
# ABC$DEF