Hướng dẫn how do i change the only second occurrence of a string in python? - làm cách nào để thay đổi lần xuất hiện thứ hai duy nhất của một chuỗi trong python?

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]
1

Cá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

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.

Đâ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.

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-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'
0

5371 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'
1

Tô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.Haider

Tô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'
2

6781 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

Làm thế nào để bạn thay đổi sự xuất hiện thứ hai của một nhân vật trong Python?

Đầu vào: S = Hồi GeekSforGeeks, ch [] = {'g', 'e', ​​'k'}, n = 2, thay thế_character = '#'.
Đầu ra: GE#KSFOR#EE#S ..
Giải thích: Trong chuỗi đã cho, sự xuất hiện thứ hai của 'g', 'e', ​​'k' được thay thế bằng '#'.

Làm thế nào để bạn thay thế một sự xuất hiện cụ thể của một chuỗi trong Python?

Cú pháp thay thế []..
Cú pháp: String.replace [cũ, mới, đếm].
Parameters:.
Giá trị trả về: Nó trả về một bản sao của chuỗi trong đó tất cả các lần xuất hiện của một chuỗi con được thay thế bằng một chuỗi con khác ..

Làm thế nào để bạn chỉ thay thế một lần xuất hiện của một ký tự trong một chuỗi trong Python?

Phương thức thay thế [] giúp thay thế sự xuất hiện của ký tự cũ đã cho bằng ký tự hoặc chuỗi con mới.Phương thức chứa các tham số như cũ [một ký tự mà bạn muốn thay thế], mới [một ký tự mới bạn muốn thay thế] và đếm [một số lần bạn muốn thay thế ký tự]. helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old[a character that you wish to replace], new[a new character you would like to replace with], and count[a number of times you want to replace the character].

Làm thế nào để bạn loại bỏ sự xuất hiện thứ hai của một chuỗi trong Python?

Xóa [] Xóa mục đầu tiên khỏi danh sách phù hợp với giá trị được chỉ định.Để loại bỏ lần xuất hiện thứ hai, bạn có thể sử dụng DEL thay vì loại bỏ.use del instead of remove.

Bài Viết Liên Quan

Chủ Đề