寫一個 Python 程序,用一個實際例子找出字元串中字元的所有出現。
Python 程序查找字元串中的字元的所有出現示例 1
這個 python 程序允許用戶輸入字元串和字元。這裡,我們使用 For 循環來迭代字元串中的每個字元。在 Python For Loop 中,我們使用 If 語句來檢查 str1 字元串中的任何字元是否等於字元 ch。如果為真,則我將值列印為輸出。記住,I 是一個索引位置(從 0 開始)。
# Python Program to find Occurrence of a Character in a String
str1 = input("Please enter your own String : ")
ch = input("Please enter your own Character : ")
for i in range(len(str1)):
if(str1[i] == ch ):
print(ch, " is Found at Position " , i + 1)
Python 字元串輸出中字元的所有出現
Please enter your own String : tutorial gateway
Please enter your own Character : t
t is Found at Position 1
t is Found at Position 3
t is Found at Position 12
Python 程序返回字元串中的字元的所有出現示例 2
這個 Python 顯示字元串程序中字元的所有出現與上面相同。然而,我們只是將循環的替換為循環的。
# Python Program to find Occurrence of a Character in a String
str1 = input("Please enter your own String : ")
ch = input("Please enter your own Character : ")
i = 0
while(i < len(str1)):
if(str1[i] == ch ):
print(ch, " is Found at Position " , i + 1)
i = i + 1
Python 中所有字元出現在一個字元串中輸出
Please enter your own String : hello world
Please enter your own Character : l
l is Found at Position 3
l is Found at Position 4
l is Found at Position 10
顯示字元串中的字元總出現次數的 Python 程序示例 3
這個 Python 查找字元串中的字元的所有出現與第一個示例相同。但是,在這個 python 程序中,我們使用了函數的概念來分離 Python 邏輯。
# Python Program to find Occurrence of a Character in a String
def all_Occurrence(ch, str1):
for i in range(len(str1)):
if(str1[i] == ch ):
print(ch, " is Found at Position " , i + 1)
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
all_Occurrence(char, string)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/259244.html