簡體   English   中英

如何 go 在 Python 的字符串中返回一個字符

[英]How to go back a character in a string in Python

我想弄清楚的是如何 go 在字符串中返回 position 。 假設我有一個單詞並且我正在檢查每個字母,但是一旦我到達“Y”,我需要檢查之前的字符是否是元音。 (我是這門語言的初學者,所以我正在嘗試練習我在 C 中所做的一些事情,這是我在大學學習的語言)。

我正在使用 For 循環來檢查單詞中的字母,但我不知道是否有任何方法可以將 go 重新放入索引中,我知道在 C 中,例如字符串被視為 ZA3CBC3F9D0CE71717171C1554E1B6一旦我到達“Y”,那將是我的word[i]i是我目前所在的 position 的索引)所以我通常會檢查"AEIOUaeiou"word[i-1] "AEIOUaeiou"i-1是 position 在我目前所在的那個之前)。 現在我不知道如何在 python 中做到這一點,如果有人能幫我一把,那就太棒了:(

一種選擇是按索引遍歷,就像您在 C 中所做的那樣:

word = "today"

for i in range(1, len(word)):
    if word[i].lower() == 'y' and word[i-1].lower() in 'aeiou':
        print(word[i-1:i+1])

另一個是zip將字符串本身移動一個字符:

for x, y in zip(word, word[1:]):
    if y.lower() == 'y' and x.lower() in 'aeiou':
        print(x+y)

您可以在這里使用正則表達式,例如標記在Y之前沒有元音的單詞,您可以使用:

inp = "blahYes"
if re.search(r'[^\WAEIOUaeiou_]Y', inp):
    print("INVALID")
else:
    print("VALID")

您可以在 C 樣式中輕松做到這一點:

vowels = ['a', 'e', 'i', 'o', 'u']

for i in range (0, len(your_string):
    if your_string[i].lower() == 'y': 
        # do your calculation here
        if your_string[i-1].lower() in vowels:
            print (f"String has vowel '{your_string[i-1]' at index {i-1} and has 'y' at i)

你可以使用your_string[i].lower() == 'y'所以它會匹配yY

或者您也可以使用enumerate function。

for index, value in enumerate(your_string):
    if val.lower() == 'y' :
        # check if index-1 was a vowel

這里已經有一個很好的答案,但我想指出一種更“類似 C”的方式來迭代字符串(或其他任何東西)。

有些人可能認為它不是 Pythonic,但在我看來,在編寫某些算法時它通常是一種好方法:

word = "today"
len_word = len(word)

vowels = "aeiou"

i = 0
while i < len_word:
    if word[i] == "y":
        if word[i-1].lower() in vowels:
            print(word[i-1])

    i += 1

這種方法為您提供了更大的靈活性,例如,您可以執行更復雜的操作,例如使用索引來回“跳躍”,但是,您還需要更加小心,不要將索引設置為超出范圍的內容可迭代的。

在 Python 中,字符串是可迭代的,因此可以獲取字符串的 [i-1] 元素

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM