Python - 保留字符串的前 N 个元素并用 K 替换剩余的元素
给定一个字符串,保留前 N 个元素并用 K 替换其余元素。
Input : test_str = ‘geeksforgeeks’, N = 5, K = “@”
Output : geeks@@@@@@@@
Explanation : First N elements retained and rest replaced by K.
Input : test_str = ‘geeksforgeeks’, N = 5, K = “*”
Output : geeks********
Explanation : First N elements retained and rest replaced by K.
方法 #1:使用 *运算符+ len() + 切片
在这里,使用切片保留N,然后通过从N中减去len()提取的总长度来提取剩余的长度,然后使用*运算符重复K char。
Python3
# Python3 code to demonstrate working of
# Retain N and Replace remaining by K
# Using * operator + len() + slicing
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing length needed
N = 4
# initializing remains char
K = "@"
# using len() and * operator to solve problem
res = test_str[:N] + K * (len(test_str) - N)
# printing result
print("The resultant string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Retain N and Replace remaining by K
# Using ljust() + slicing + len()
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing length needed
N = 4
# initializing remains char
K = "@"
# ljust assigns K to remaining string
res = test_str[:N].ljust(len(test_str), K)
# printing result
print("The resultant string : " + str(res))
输出
The original string is : geeksforgeeks
The resultant string : geek@@@@@@@@@
方法#2:使用 ljust() + 切片 + len()
在这种情况下,分配剩余字符的任务是使用 ljust 而不是 *运算符完成的。
蟒蛇3
# Python3 code to demonstrate working of
# Retain N and Replace remaining by K
# Using ljust() + slicing + len()
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing length needed
N = 4
# initializing remains char
K = "@"
# ljust assigns K to remaining string
res = test_str[:N].ljust(len(test_str), K)
# printing result
print("The resultant string : " + str(res))
输出
The original string is : geeksforgeeks
The resultant string : geek@@@@@@@@@