Tôi muốn thay thế sự xuất hiện của một chuỗi con trong một chuỗi.
Phải có một cái gì đó tương đương với những gì tôi muốn làm
import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
1Cách đơn giản và pythonic nhất để đạt được điều này là gì?
Tại sao không sao chép: Tôi không muốn sử dụng Regex cho phương pháp này và hầu hết các câu trả lời cho các câu hỏi tương tự mà tôi tìm thấy chỉ là tước Regex hoặc chức năng thực sự phức tạp. Tôi thực sự muốn đơn giản nhất có thể và không phải là giải pháp Regex. I don't want to use regex for this approach and most of answers to similar questions I found are just regex stripping or really complex function. I really want as simple as possible and not regex solution.
hỏi ngày 29 tháng 1 năm 2016 lúc 18:31Jan 29, 2016 at 18:31
Aleskvaaleskvaaleskva
1.4742 Huy hiệu vàng19 Huy hiệu bạc37 Huy hiệu đồng2 gold badges19 silver badges37 bronze badges
3
Bạn có thể sử dụng vòng lặp thời gian với
import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
2 để tìm sự xuất hiện thứ n nếu nó tồn tại và sử dụng vị trí đó để tạo chuỗi mới:def nth_repl[s, sub, repl, n]:
find = s.find[sub]
# If find is not -1 we have found at least one match for the substring
i = find != -1
# loop util we find the nth or we find no match
while find != -1 and i != n:
# find + 1 means we start searching from after the last match
find = s.find[sub, find + 1]
i += 1
# If i is equal to n we found nth match so replace
if i == n:
return s[:find] + repl + s[find+len[sub]:]
return s
Example:
In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl[s, "bar","replaced",3]
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl[s, "foo","replaced",3]
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl[s, "foo","replaced",5]
Out[17]: 'foobarfoofoobarbar'
wjandrea
25.1k8 Huy hiệu vàng53 Huy hiệu bạc74 Huy hiệu đồng8 gold badges53 silver badges74 bronze badges
Đã trả lời ngày 29 tháng 1 năm 2016 lúc 19:23Jan 29, 2016 at 19:23
2
Tôi sử dụng chức năng đơn giản, liệt kê tất cả các lần xuất hiện, chọn vị trí của một thứ n và sử dụng nó để chia chuỗi ban đầu thành hai chuỗi con. Sau đó, nó thay thế lần xuất hiện đầu tiên trong chuỗi con thứ hai và tham gia các chuỗi con trở lại vào chuỗi mới:
import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
Đối với các biến này:
string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
outputs:
ababababCDabababab
Notes:
Biến
3 thực sự là danh sách các vị trí của các trận đấu, trong đó bạn chọn thứ n. Nhưng chỉ số mục Danh sách bắt đầu vớiimport re def replacenth[string, sub, wanted, n]: where = [m.start[] for m in re.finditer[sub, string]][n-1] before = string[:where] after = string[where:] after = after.replace[sub, wanted, 1] newString = before + after print[newString]
4 thường, không phải vớiimport re def replacenth[string, sub, wanted, n]: where = [m.start[] for m in re.finditer[sub, string]][n-1] before = string[:where] after = string[where:] after = after.replace[sub, wanted, 1] newString = before + after print[newString]
5. Do đó, có một chỉ sốimport re def replacenth[string, sub, wanted, n]: where = [m.start[] for m in re.finditer[sub, string]][n-1] before = string[:where] after = string[where:] after = after.replace[sub, wanted, 1] newString = before + after print[newString]
6 và biếnimport re def replacenth[string, sub, wanted, n]: where = [m.start[] for m in re.finditer[sub, string]][n-1] before = string[:where] after = string[where:] after = after.replace[sub, wanted, 1] newString = before + after print[newString]
7 là chuỗi con thứ n thực tế. Ví dụ của tôi tìm thấy chuỗi thứ 5. Nếu bạn sử dụng chỉ sốimport re def replacenth[string, sub, wanted, n]: where = [m.start[] for m in re.finditer[sub, string]][n-1] before = string[:where] after = string[where:] after = after.replace[sub, wanted, 1] newString = before + after print[newString]
7 và muốn tìm vị trí thứ 5, bạn sẽ cầnimport re def replacenth[string, sub, wanted, n]: where = [m.start[] for m in re.finditer[sub, string]][n-1] before = string[:where] after = string[where:] after = after.replace[sub, wanted, 1] newString = before + after print[newString]
7 để trở thànhimport re def replacenth[string, sub, wanted, n]: where = [m.start[] for m in re.finditer[sub, string]][n-1] before = string[:where] after = string[where:] after = after.replace[sub, wanted, 1] newString = before + after print[newString]
0. Mà bạn sử dụng thường phụ thuộc vào chức năng, tạo rastring = 'ababababababababab' sub = 'ab' wanted = 'CD' n = 5
7 của chúng tôi.import re def replacenth[string, sub, wanted, n]: where = [m.start[] for m in re.finditer[sub, string]][n-1] before = string[:where] after = string[where:] after = after.replace[sub, wanted, 1] newString = before + after print[newString]
Đây phải là cách đơn giản nhất, nhưng có lẽ đó không phải là cách pythonic nhất, bởi vì xây dựng biến
3 cần nhập thư việnimport re def replacenth[string, sub, wanted, n]: where = [m.start[] for m in re.finditer[sub, string]][n-1] before = string[:where] after = string[where:] after = after.replace[sub, wanted, 1] newString = before + after print[newString]
3. Có lẽ ai đó sẽ tìm thấy nhiều cách hơn nữa.string = 'ababababababababab' sub = 'ab' wanted = 'CD' n = 5
Các nguồn và một số liên kết ngoài ra:
3 Xây dựng: Làm thế nào để tìm thấy tất cả các lần xuất hiện của một nền tảng?import re def replacenth[string, sub, wanted, n]: where = [m.start[] for m in re.finditer[sub, string]][n-1] before = string[:where] after = string[where:] after = after.replace[sub, wanted, 1] newString = before + after print[newString]
- Chuỗi chia tách: //www.daniweb.com/programming/software-development/threads/452362/replace-nth-cururrence-of-an-sub-string-in-a-string
- Câu hỏi tương tự: Tìm sự xuất hiện thứ n của chuỗi con trong chuỗi
Belter
3.3154 Huy hiệu vàng40 Huy hiệu bạc52 Huy hiệu đồng4 gold badges40 silver badges52 bronze badges
Đã trả lời ngày 29 tháng 1 năm 2016 lúc 18:31Jan 29, 2016 at 18:31
Aleskvaaleskvaaleskva
1.4742 Huy hiệu vàng19 Huy hiệu bạc37 Huy hiệu đồng2 gold badges19 silver badges37 bronze badges
2
Bạn có thể sử dụng vòng lặp thời gian với
import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
2 để tìm sự xuất hiện thứ n nếu nó tồn tại và sử dụng vị trí đó để tạo chuỗi mới:def nth_replace[string, old, new, n=1, option='only nth']:
"""
This function replaces occurrences of string 'old' with string 'new'.
There are three types of replacement of string 'old':
1] 'only nth' replaces only nth occurrence [default].
2] 'all left' replaces nth occurrence and all occurrences to the left.
3] 'all right' replaces nth occurrence and all occurrences to the right.
"""
if option == 'only nth':
left_join = old
right_join = old
elif option == 'all left':
left_join = new
right_join = old
elif option == 'all right':
left_join = old
right_join = new
else:
print["Invalid option. Please choose from: 'only nth' [default], 'all left' or 'all right'"]
return None
groups = string.split[old]
nth_split = [left_join.join[groups[:n]], right_join.join[groups[n:]]]
return new.join[nth_split]
wjandreaApr 2, 2017 at 18:27
25.1k8 Huy hiệu vàng53 Huy hiệu bạc74 Huy hiệu đồngCapedHero
Đã trả lời ngày 29 tháng 1 năm 2016 lúc 19:231 gold badge9 silver badges20 bronze badges
Tôi sử dụng chức năng đơn giản, liệt kê tất cả các lần xuất hiện, chọn vị trí của một thứ n và sử dụng nó để chia chuỗi ban đầu thành hai chuỗi con. Sau đó, nó thay thế lần xuất hiện đầu tiên trong chuỗi con thứ hai và tham gia các chuỗi con trở lại vào chuỗi mới:
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n - 1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted]
newString = before + after
return newString
Đối với các biến này:
Biến
import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
3 thực sự là danh sách các vị trí của các trận đấu, trong đó bạn chọn thứ n. Nhưng chỉ số mục Danh sách bắt đầu với import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
4 thường, không phải với import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
5. Do đó, có một chỉ số import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
6 và biến import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
7 là chuỗi con thứ n thực tế. Ví dụ của tôi tìm thấy chuỗi thứ 5. Nếu bạn sử dụng chỉ số import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
7 và muốn tìm vị trí thứ 5, bạn sẽ cần import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
7 để trở thành string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
0. Mà bạn sử dụng thường phụ thuộc vào chức năng, tạo ra import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
7 của chúng tôi.Mar 20, 2017 at 9:43
1
Đây phải là cách đơn giản nhất, nhưng có lẽ đó không phải là cách pythonic nhất, bởi vì xây dựng biến
import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
3 cần nhập thư viện string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
3. Có lẽ ai đó sẽ tìm thấy nhiều cách hơn nữa.import re
def replacenth[string, sub, wanted, n]:
pattern = re.compile[sub]
where = [m for m in pattern.finditer[string]][n-1]
before = string[:where.start[]]
after = string[where.end[]:]
newString = before + wanted + after
return newString
replacenth['abdsahd124njhdasjk124ndjaksnd124ndjkas', '1.*?n', '15', 1]
Các nguồn và một số liên kết ngoài ra:
import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
3 Xây dựng: Làm thế nào để tìm thấy tất cả các lần xuất hiện của một nền tảng?Chuỗi chia tách: //www.daniweb.com/programming/software-development/threads/452362/replace-nth-cururrence-of-an-sub-string-in-a-stringMar 12, 2019 at 11:24
J.WarrenJ.WarrenJ.Warren
Câu hỏi tương tự: Tìm sự xuất hiện thứ n của chuỗi con trong chuỗi1 gold badge4 silver badges14 bronze badges
def replace_nth_occurance[some_str, original, replacement, n]:
""" Replace nth occurance of a string with another string
"""
all_replaced = some_str.replace[original, replacement, n] # Replace all originals up to [including] nth occurance and assign it to the variable.
for i in range[n]:
first_originals_back = all_replaced.replace[replacement, original, i] # Restore originals up to nth occurance [not including nth]
return first_originals_back
BelterNov 22, 2018 at 6:41
3.3154 Huy hiệu vàng40 Huy hiệu bạc52 Huy hiệu đồngvineeshvs
Đã trả lời ngày 29 tháng 1 năm 2016 lúc 18:317 silver badges30 bronze badges
Tôi đã đưa ra bên dưới, trong đó xem xét các tùy chọn để thay thế tất cả các chuỗi 'cũ' ở bên trái hoặc bên phải. Đương nhiên, không có tùy chọn để thay thế tất cả các lần xuất hiện, vì Standard Str.Replace hoạt động hoàn hảo.
def Nreplacer[string,srch,rplc,n]:
Sstring = string.split[srch]
#first check if substring is even present n times
#then paste the part before the nth substring to the part after the nth substring
#, with the replacement inbetween
if len[Sstring] > [n]:
return f'{srch.join[Sstring[:[n]]]}{rplc}{srch.join[Sstring[n:]]}'
else:
return string
Đã trả lời ngày 2 tháng 4 năm 2017 lúc 18:27Feb 3, 2021 at 17:58
Capedherocapedhero
In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl[s, "bar","replaced",3]
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl[s, "foo","replaced",3]
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl[s, "foo","replaced",5]
Out[17]: 'foobarfoofoobarbar'
05371 Huy hiệu vàng9 Huy hiệu bạc 20 Huy hiệu Đồng
Câu trả lời cuối cùng là gần như hoàn hảo - chỉ có một hiệu chỉnh:Feb 23, 2021 at 17:25
Các chuỗi sau phải được lưu trữ trong biến này một lần nữa sau khi thay thế. Cảm ơn bạn vì giải pháp tuyệt vời!
Đã trả lời ngày 20 tháng 3 năm 2017 lúc 9:43
In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl[s, "bar","replaced",3]
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl[s, "foo","replaced",3]
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl[s, "foo","replaced",5]
Out[17]: 'foobarfoofoobarbar'
1Tôi đã điều chỉnh câu trả lời của @Aleskva để làm việc tốt hơn với Regex và Wildcards:Jul 20, 2021 at 14:46
Điều này cho
string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
5. Lưu ý việc sử dụng string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
6 để làm cho truy vấn không màu gu.HaiderTôi nhận ra rằng câu hỏi nói rõ ràng rằng họ không muốn sử dụng Regex, tuy nhiên có thể hữu ích khi có thể sử dụng các ký tự đại diện theo cách rõ ràng [do đó câu trả lời của tôi].3 silver badges8 bronze badges
Đã trả lời ngày 12 tháng 3 năm 2019 lúc 11:24
In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl[s, "bar","replaced",3]
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl[s, "foo","replaced",3]
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl[s, "foo","replaced",5]
Out[17]: 'foobarfoofoobarbar'
26781 Huy hiệu vàng4 Huy hiệu bạc14 Huy hiệu đồng
Đã trả lời ngày 22 tháng 11 năm 2018 lúc 6:41Dec 14, 2021 at 19:39
Vineeshvsvineeshvs
In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl[s, "bar","replaced",3]
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl[s, "foo","replaced",3]
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl[s, "foo","replaced",5]
Out[17]: 'foobarfoofoobarbar'
3
4217 Huy hiệu bạc 30 Huy hiệu Đồng
Một chút muộn với bữa tiệc, nhưng tôi sẽ xem xét theo cách này khá pythonia [theo như tôi hiểu ý nghĩa của điều đó] và nó không yêu cầu một vòng lặp hoặc quầy6 silver badges19 bronze badges
Đã trả lời ngày 10 tháng 5 năm 2018 lúc 14:37May 10, 2018 at 14:37
Giải pháp chung: Thay thế bất kỳ [các] phiên bản được chỉ định của một chuỗi con [mẫu] bằng một chuỗi khác.
In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl[s, "bar","replaced",3]
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl[s, "foo","replaced",3]
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl[s, "foo","replaced",5]
Out[17]: 'foobarfoofoobarbar'
4Đã trả lời ngày 3 tháng 5 năm 2020 lúc 12:15May 3, 2020 at 12:15
jpfjpfjpf
1.43312 huy hiệu bạc21 Huy hiệu đồng12 silver badges21 bronze badges
Theo quan điểm của tôi
In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl[s, "bar","replaced",3]
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl[s, "foo","replaced",3]
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl[s, "foo","replaced",5]
Out[17]: 'foobarfoofoobarbar'
5Đầu ra
In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl[s, "bar","replaced",3]
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl[s, "foo","replaced",3]
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl[s, "foo","replaced",5]
Out[17]: 'foobarfoofoobarbar'
6Đã trả lời ngày 22 tháng 9 năm 2020 lúc 6:19Sep 22, 2020 at 6:19
Thanh lịch và ngắn:
In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl[s, "bar","replaced",3]
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl[s, "foo","replaced",3]
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl[s, "foo","replaced",5]
Out[17]: 'foobarfoofoobarbar'
7Đã trả lời ngày 2 tháng 10 năm 2020 lúc 10:48Oct 2, 2020 at 10:48
Adir Abargiladir Abargiladir abargil
5.0503 Huy hiệu vàng18 Huy hiệu bạc25 Huy hiệu Đồng3 gold badges18 silver badges25 bronze badges
1
Chỉ có một vài câu trả lời không phải là regex và muốn cung cấp giải pháp của riêng tôi mà tôi nghĩ là đơn giản và dễ hiểu hơn. Tạo một chuỗi mới và đếm cho sự xuất hiện thứ n của nhân vật bạn muốn thay thế.
In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl[s, "bar","replaced",3]
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl[s, "foo","replaced",3]
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl[s, "foo","replaced",5]
Out[17]: 'foobarfoofoobarbar'
8Đã trả lời ngày 12 tháng 1 năm 2021 lúc 15:49Jan 12, 2021 at 15:49
MeshimeshiMeshi
4304 Huy hiệu bạc15 Huy hiệu Đồng4 silver badges15 bronze badges
Tôi có một lớp lót nếu Regex của bạn là
string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
7 và bạn cần thay thế nó bằng string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
8:if your regex is
string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
7 and you need to replace it with string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
8:In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl[s, "bar","replaced",3]
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl[s, "foo","replaced",3]
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl[s, "foo","replaced",5]
Out[17]: 'foobarfoofoobarbar'
9Đã trả lời ngày 19 tháng 6 lúc 13:41Jun 19 at 13:41
.
Giải pháp được cung cấp bởi Padraic Cickyham rất đơn giản và hoạt động, ngoại trừ lỗi được đề cập bởi @haider.
Để sửa lỗi, có một giải pháp dễ dàng hơn so với giải pháp được cung cấp bởi Haider: Thay đổi cách cập nhật giá trị của
string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
9. Nó không nên được tăng lên nếu chuỗi được tìm kiếm chưa được tìm thấy.Ngoài ra, có một lỗi nếu
import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
7 nhỏ hơn 1 [không nên xảy ra, nhưng có lẽ tốt hơn để kiểm tra].Do đó, giải pháp được sửa đổi rất nhẹ là:
import re
def replacenth[string, sub, wanted, n]:
where = [m.start[] for m in re.finditer[sub, string]][n-1]
before = string[:where]
after = string[where:]
after = after.replace[sub, wanted, 1]
newString = before + after
print[newString]
0Đã trả lời ngày 5 tháng 9 lúc 10:55Sep 5 at 10:55
2-REC2-REC2-REC
Phù hiệu bằng đồng 2122 bronze badges