Python – 在字符串中的第 i 个索引处替换为 K
给定一个字符串,用 K 值替换第 i 个索引。
Input : test_str = ‘geeks5geeks’, K = ‘7’, i = 5
Output : ‘geeks7geeks’
Explanation : Element is 5, converted to 7 on ith index.
Input : test_str = ‘geeks5geeks’, K = ‘7’, i = 6
Output : ‘geeks56eeks’
Explanation : Element is g, converted to 7 on ith index.
方法#1:使用字符串切片
在此,我们使用字符串切片方法对 pre 字符串进行切片,直到 i,然后添加 K,然后添加 post 值。
Python3
# Python3 code to demonstrate working of
# Replace to K at ith Index in String
# using string slicing
# initializing strings
test_str = 'geeks5geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '4'
# initializing i
i = 5
# the replaced result
res = test_str[: i] + K + test_str[i + 1:]
# printing result
print("The constructed string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Replace to K at ith Index in String
# using join() + generator expression
# initializing strings
test_str = 'geeks5geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '4'
# initializing i
i = 5
# the replaced result
res = ''.join(test_str[idx] if idx != i else K for idx in range(len(test_str)))
# printing result
print("The constructed string : " + str(res))
输出
The original string is : geeks5geeks
The constructed string : geeks4geeks
方法 #2:使用 join() + 生成器表达式
在此,我们执行检查第 i 个索引并有条件地附加 K 的任务,使用生成器表达式并使用 join() 将结果转换为字符串。
Python3
# Python3 code to demonstrate working of
# Replace to K at ith Index in String
# using join() + generator expression
# initializing strings
test_str = 'geeks5geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '4'
# initializing i
i = 5
# the replaced result
res = ''.join(test_str[idx] if idx != i else K for idx in range(len(test_str)))
# printing result
print("The constructed string : " + str(res))
输出
The original string is : geeks5geeks
The constructed string : geeks4geeks