単語をアルファベット順に並べ替えるPythonプログラム

Python

 

この例では、単語を辞書式順序(アルファベット順)で並べ替える方法を示します。

ソースコード

# Program to sort alphabetically the words form a string provided by the user

my_str = "Hello this Is an Example With cased letters"

# To take input from the user
#my_str = input("Enter a string: ")

# breakdown the string into a list of words
words = [word.lower() for word in my_str.split()]

# sort the list
words.sort()

# display the sorted words

print("The sorted words are:")
for word in words:
   print(word)

出力

The sorted words are:
an
cased
example
hello
is
letters
this
with

注意: プログラムをテストするには、の値を変更します my_str

このプログラムでは、ソートする文字列を格納します my_str。 split()メソッドを使用して、文字列が単語のリストに変換されます。 split()メソッドは、文字列を空白で分割します。

次に、sort()メソッドを使用して単語のリストが並べ替えられ、すべての単語が表示されます。

Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です