Python – 除第一个字符外,用 K 替换出现次数
给定一个字符串,任务是编写一个Python程序,在第一个索引处用 K 个字符替换出现的字符,但在第一个索引处除外。
例子:
Input : test_str = 'geeksforgeeksforgeeks', K = '@'
Output : geeksfor@eeksfor@eeks
Explanation : All occurrences of g are converted to @ except 0th index.
Input : test_str = 'geeksforgeeks', K = '#'
Output : geeksfor#eeks
Explanation : All occurrences of g are converted to # except 0th index.
方法#1:使用切片+replace()
在此,我们执行用出现在第 1 个索引处的字符的 K 替换第 2 个字符的整个字符串的任务。结果是前缀由第一个字符连接。
Python3
# Python3 code to demonstrate working of
# Replace occurrences by K except first character
# Using slicing + replace()
# initializing string
test_str = 'geeksforgeeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '$'
# replacing using replace()
res = test_str[0] + test_str[1:].replace(test_str[0], K)
# printing result
print("Replaced String : " + str(res))
Python3
# Python3 code to demonstrate working of
# Replace occurrences by K except first character
# Using replace()
# initializing string
test_str = 'geeksforgeeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '$'
# replacing using replace()
res = test_str.replace(test_str[0], K).replace(K, test_str[0], 1)
# printing result
print("Replaced String : " + str(res))
输出:
The original string is : geeksforgeeksforgeeks
Replaced String : geeksfor$eeksfor$eeks
方法#2:使用replace()
在这种情况下,replace() 被调用两次以替换所有出现的任务,然后只是反向替换第一次出现。
蟒蛇3
# Python3 code to demonstrate working of
# Replace occurrences by K except first character
# Using replace()
# initializing string
test_str = 'geeksforgeeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '$'
# replacing using replace()
res = test_str.replace(test_str[0], K).replace(K, test_str[0], 1)
# printing result
print("Replaced String : " + str(res))
输出:
The original string is : geeksforgeeksforgeeks
Replaced String : geeksfor$eeksfor$eeks