溫馨提示×

python中怎么查找指定字符

小億
181
2023-12-07 20:47:37
欄目: 編程語言

在Python中,可以使用字符串的find()方法來查找指定字符。find()方法返回指定字符在字符串中第一次出現的位置,如果沒有找到則返回-1。

以下是使用find()方法查找指定字符的示例:

string = "Hello, World!"
character = "o"

index = string.find(character)

if index != -1:
    print(f"The character '{character}' was found at index {index}.")
else:
    print(f"The character '{character}' was not found in the string.")

輸出:

The character 'o' was found at index 4.

此外,還可以使用index()方法來查找指定字符。index()方法的用法與find()方法類似,但是如果指定字符不存在于字符串中,index()方法將會拋出一個ValueError異常。

string = "Hello, World!"
character = "o"

try:
    index = string.index(character)
    print(f"The character '{character}' was found at index {index}.")
except ValueError:
    print(f"The character '{character}' was not found in the string.")

輸出:

The character 'o' was found at index 4.

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女