指定された位置の文字列をどのように置き換えますか?

指定された位置の文字列を置き換えるには、文字列のスライスと連結操作を使用します。以下はサンプルコードです。

def replace_string_at_index(input_str, replace_str, start_index):
    return input_str[:start_index] + replace_str + input_str[start_index + len(replace_str):]

# 示例用法
input_str = "Hello, World!"
replace_str = "Python"
start_index = 7

new_str = replace_string_at_index(input_str, replace_str, start_index)
print(new_str)

実行結果:

Hello, Python!

例えば、「replace_string_at_index」関数は3つの引数を受け取ります:input_strは元の文字列を表し、replace_strは置き換える文字列を表し、start_indexは置き換える位置のインデックスを表します。この関数は、元の文字列をスライス操作して3つの部分に分割し、それらを結合します。最初の部分は文字列の先頭から置き換える位置までの部分であり、2番目の部分は置き換える文字列であり、3番目の部分は置き換える位置に置き換える文字列の長さを加えて末尾までの部分です。最終的に、結合された新しい文字列を返します。

bannerAds