Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonプログラムで一般的でない文字と連結された文字列


2つの文字列を指定し、両方の文字列から一意の文字を含む新しい文字列を取得することを目標としています。たとえば、2つの文字列がある場合 hafeez およびカリーム 次に、2つの文字列から生成される新しい文字列は hfzkrmです。 。 2つの文字列から異なる文字を取得することを目指しています。私の手順に従う前に、ロジックについて一度考えてください。

プログラムのロジックについて考えることができない場合は、以下の手順に従ってください。

アルゴリズム

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

結論

チュートリアルについて疑問がある場合は、コメントセクションにその旨を記載してください。


  1. Pythonで指定されたインデックスを使用して文字列をシャッフルするプログラム

    文字列sとインデックスindのリストがあり、それらは同じ長さであるとします。文字列sは、位置iの文字が最終文字列のindexes[i]に移動するようにシャッフルされます。最後の文字列を見つける必要があります。 したがって、入力がs =ktoalak ind =[0,5,1,6,2,4,3]の場合、出力は「コルカタ」になります これを解決するには、次の手順に従います- fin_str:=サイズがsと同じで、0で埋められるリスト sの各インデックスiと文字vについて、実行します fin_str [ind [i]]:=v fin_strに存在する各文字を結合し

  2. 文字列にすべての一意の文字が含まれているかどうかを確認するPythonプログラム

    この記事では、特定の問題ステートメントを解決するための解決策とアプローチについて学習します。 問題の説明 sring入力が与えられた場合、文字列にすべての一意の文字が含まれているかどうかを確認する必要があります。 アプローチ ブール値の配列を作成します。ここで、インデックスiの変数フラグは、アルファベットの文字iが文字列に含まれているかどうかを示します。 この文字に2回目に遭遇したとき、文字列文字は一意ではなくなったため、すぐにfalseを返すことができます。 文字列の長さがアルファベットに表示される一意の文字数の値を超える場合も、falseを返すことができます。 文