簡體   English   中英

沒有非字母符號的反向字符串

[英]Reverse string without non letters symbol

我只需要反轉每個單詞中的字母。 單詞和非字母符號的順序必須保持不變。 我有一個function,但是把position這個詞改了。

def reverse_string(st):
    stack = []
    for el in st:
        if el.isalpha():
            stack.append(el)
    result = ''
    for el in st:
        if el.isalpha():
            result += stack.pop()
        else:
            result += el
    return result

輸入字符串:

b3ghcd hg#tyj%h

預期 output 字符串:

d3chgb hj#ytg%h

或者,您可以嘗試以下方法,它僅創建字母字符的反向列表,然后將非字母字符插入到它們各自的位置,並將序列作為字符串返回。

def rev_str(s):
    x = list(filter(str.isalpha, s[::-1]))
    for i,s_ in enumerate(s):
        if not s_.isalpha():
            x.insert(i, s_)
    return ''.join(x)

instr = 'b3ghcd hg#tyj%h'
outstr = ' '.join(rev_str(s) for s in instr.split())

print(outstr)
d3chgb hj#ytg%h

你真的很親密。 您的代碼不起作用,因為您將還原應用於整個字符串,而不是一次一個單詞執行:但是只需添加一個額外的步驟,將輸入字符串拆分為空格(我假設空格是定義單詞的地方輸入)你會得到你想要的結果:

def reverse_string(st):
    return ' '.join(reverse_word(word) for word in st.split())

def reverse_word(st):
    stack = []
    for el in st:
        if el.isalpha():
            stack.append(el)
    result = ''
    for el in st:
        if el.isalpha():
            result += stack.pop()
        else:
            result += el
    return result

instr = 'b3ghcd hg#tyj%h'

print(reverse_string(instr)) # prints 'd3chgb hj#ytg%h'

注意:您可以使用列表推導的一些內置函數對您的代碼進行 Python 化處理。 在這種情況下,您將替換stack的構建。

stack = []
    for el in st:
        if el.isalpha():
            stack.append(el)

對於以下其中一項:

stack = [el for el in st if el.isalpha()]stack = list(filter(str.isalpha, st))

使用您提供的 function,一種方法是:

import re

def reverse_word(st):
    stack = []
    for el in st:
        if el.isalpha():
            stack.append(el)
    result = ''
    for el in st:
        if el.isalpha():
            result += stack.pop()
        else:
            result += el
    return result

def reverse_string(st):
    return re.sub(r'\S+', lambda match: reverse_word(match.group()), st)

print(reverse_string("b3ghcd hg#tyj%h"))
# "d3chgb hj#ytg%h"

沒有經過全面測試,您可能想使用例如[^\s,.?;;]或類似的而不是\S ,具體取決於您正在處理的“句子”類型。

暫無
暫無

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

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