寫一個 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-hant/n/259244.html