Python:字符串替换索引

时间:2016-08-09 16:36:22

标签: python string python-3.x

我的意思是,我想将str[9:11]替换为另一个字符串。 如果我做str.replace(str[9:11], "###")它不起作用,因为序列[9:11]可能不止一次。 如果str是"cdabcjkewabcef",我会得到"cd###jkew###ef",但我只想替换第二个。

6 个答案:

答案 0 :(得分:8)

你可以做到

import os
import pyodbc

print ("Connecting via ODBC")

conn = pyodbc.connect('DSN=dsn', autocommit=True)

print ("Connected!\n")

 inputdir = 'C:\\path'
cursor = conn.cursor()

for script in os.listdir(inputdir):

   with open(inputdir+'\\' + script,'r') as inserts:

       sqlScript = inserts.readlines()

       sql = (" ".join(sqlScript))

       cursor.execute(sql)

       print (script)

conn.close()

print ('Run Complete!')

应该比在大字符串上加入s="cdabcjkewabcef" snew="".join((s[:9],"###",s[12:])) 更快

答案 1 :(得分:2)

您可以通过以下方式实现此目的:

yourString = "Hello"
yourIndexToReplace = 1 #e letter
newLetter = 'x'
yourStringNew="".join((yourString[:yourIndexToReplace],newLetter,yourString[yourIndexToReplace+1:]))

答案 2 :(得分:1)

给定txt和s - 要替换​​的字符串:

txt.replace(s, "***", 1).replace(s, "###").replace("***", s)

另一种方式:

txt[::-1].replace(s[::-1], "###", 1)[::-1]

答案 3 :(得分:1)

您可以将join()与子字符串一起使用。

s = 'cdabcjkewabcef'
sequence = '###'
indicies = (9,11)
print sequence.join([s[:indicies[0]-1], s[indicies[1]:]])
>>> 'cdabcjke###cef'

答案 4 :(得分:1)

str = "cdabcjkewabcef"
print((str[::-1].replace('cba','###',1))[::-1])

答案 5 :(得分:0)

以下是示例代码:

word = "astalavista"
index = 0
newword = ""
addon = "xyz"
while index < 8:
    newword = newword + word[index]
    index += 1
    ind = index

i = 0
while i < len(addon):
    newword = newword + addon[i]
    i += 1

while ind < len(word):
    newword = newword + word[ind]
    ind += 1

print newword