在Python程序中串接不常见字符的字符串
我们给出了两个字符串,我们的目标是从两个字符串中获得一个具有唯一字符的新字符串。假设,如果我们有两个字符串hafeez和kareem,那么将从这两个字符串生成的新字符串是hfzkrm。我们的目标是从两个字符串中获得不同的字符。在执行我的步骤之前,请先考虑一下逻辑。
如果您无法考虑程序的逻辑,请执行以下步骤。
算法
1. Initialize the string.
2. Initialize an empty string.
3. Loop over the first string.
3.1. Check whether the current char is in the second string or not.
3.1.1. If it's not in the second string, then add it to the empty string.
4. Loop over the second string.
4.1. Check whether the current char is in the first string or not.
4.1.1. If it's not in the first string, then add it to the empty string.
5. Print the resultant string.让我们检查程序代码。
示例
## initializing the strings
string_1 = "hafeez"
string_2 = "kareem"
## initializing an empty string
new_string = ""
## iterating through the first string
for char in string_1:
## checking is the char is in string_2 or not
if char not in string_2:
## adding the char to new_string
new_string += char
## iterating through the second string
for char in string_2:
## checking is the char is in string_1 or not
if char not in string_1:
## adding the char to new_string
new_string += char
## printing the new_string
print(f"New String: {new_string}")输出结果
如果运行上述程序,将得到以下输出。
New String: hfzkrm
结论
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短