首页 > 解决方案 > 提取后反向打印字符串

问题描述

我正在尝试创建一个程序,其中用户输入一个包含两个“!”的语句 围绕一个字符串。(例如:大家好!这是一个测试!再见。)我要抓住两个感叹号内的字符串,然后一个字母一个字母地反向打印。 我已经能够找到包含该语句的起点和终点,但是我很难创建一个索引,该索引将userstring反向循环遍历我的变量并打印。

test = input('Enter a string with two "!" surrounding portion of the string:')
expoint = test.find('!')
     #print (expoint)
twoexpoint = test.find('!', expoint+1)
     #print (twoexpoint)
userstring = test[expoint+1 : twoexpoint]
     #print(userstring)


number = 0
while number < len(userstring) :
    letter = [twoexpoint - 1]
    print (letter)
    number += 1

标签: pythonpython-3.xstringreverse

解决方案


解释我们使用正则表达式来查找模式,然后我们循环每次出现,并用反转的字符串替换出现。我们可以在 python 中反转字符串mystring[::-1](也适用于列表)

Python re 文档非常有用,您将在编码器道路上一直需要它:)。快乐编码!

很有用的文章 ,看看吧!

import re # I recommend using regex

def reverse_string(a):
    matches = re.findall(r'\!(.*?)\!', a)
    for match in matches:
        print("Match found", match)
        print("Match reversed", match[::-1])
        for i in match[::-1]:
            print(i)

In [3]: reverse_string('test test !test! !123asd!')
Match found test
Match reversed tset
t
s
e
t
Match found 123asd
Match reversed dsa321
d
s
a
3
2
1

推荐阅读