Python – 列印字母到 N
Python 語言為使用者提供了從基本計算到複雜計算的多種用途。根據使用者指定的“N”值,程式會列印到“N”的字母。列印一定範圍內的字母看似一項簡單的任務,但在建立程式時,會涉及一些繁瑣的過程。Python 方法使用各種功能來列印到 N 的字母。此演算法是機器學習技術的基石。
列印字母到 N
英語共有 26 個字母,當範圍 N 指定為 9 時,Python 程式將列印到“i”。例如,當範圍指定為 9 時,輸出為 a、b、c、d、e、f、g、h、i。
方法
方法 1:使用 string 模組
方法 2:使用迭代方法
方法 3:使用 join 函式
方法 1:使用 string 模組列印到 N 的字母的 Python 程式
string 模組專門用於使用“N”值列印字母範圍。該模組為使用者提供由 ASCII 字元組成的預定義常量。當使用小寫函式時,它會以小寫字母提供字母。
演算法
步驟 1 – 匯入 string 模組。
步驟 2 – 將輸入變數初始化為整數資料型別。
步驟 3 – 使用 for 迴圈迭代使用者指定的範圍內的值,從 0 到 string1。
步驟 4 – 使用 string 模組中的 ascii_lowercase() 函式,以小寫形式顯示輸出。
步驟 5 – 冒號將輕鬆截斷列表。
步驟 6 – 垂直列印字母列表。
示例
#importing the string module import string #The range needs to be mentioned here as “N” string1 = 5 #for loop is used to iterate through the given input #the ascii_lowercase function is used to print the result in lowercase for alphabet in string.ascii_uppercase[:string1]: #Print statement will return the list of alphabets according to the range value print(alphabet)
輸出
A B C D E
方法 2:使用迭代方法列印到 N 的字母的 Python 程式
字母的列印不使用任何內建模組,而是使用 for 迴圈。for 迴圈將迭代使用者給定的範圍內的值。
演算法
步驟 1 – 設定範圍值。
步驟 2 – for 迴圈將從 0 迭代到使用者提到的值,在本例中 N=6。
步驟 3 – 使用 chr() 函式將每個值轉換為等效的 ASCII 字元,然後新增 97。
步驟 4 – 新增值“97”,因為小寫字母從它開始。
步驟 5 – print 函式返回字母範圍。
示例
#initializing the input value range_value = 5 #for loop used to iterate through the values #range inbuilt function iterates through the value for a in range(range_value): #print the range of alphabets using the print statement print(chr(a+97))
輸出
a b c d e
方法 3:使用 join 函式列印到 N 的字母的 Python 程式
string 模組用於處理列印字串值。同時,使用 join() 函式組合所有字母。
演算法
步驟 1 – 需要匯入使用 join 函式的模組 string。
步驟 2 – 設定 string1 的值。
步驟 3 – 宣告換行符以在單獨的行中列印字母。
步驟 4 – join 函式組合到範圍“N”的英語字母的所有小寫字母。
步驟 5 – print 語句返回換行符中的字串值,直到 N 值。
示例
#initializing the string module to hold the join function
import string
#The output is printed from the range mentioned in an integer value
string1 = 6
#print statement returns the result
print('\n'.join(string.ascii_lowercase[:string1]))
輸出
a b c d e f
結論
解釋了兩種方法中使用的 string 模組,這是一個預定義庫,用於使用 ASCII 字母。程式設計師可以透過以上方法列印大寫字母,方法是使用 uppercase() 函式。透過這種方式,程式設計師可以輕鬆理解字串到一定範圍的實現過程。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP