python - 提取后反向打印字符串
问题描述
我正在尝试创建一个程序,其中用户输入一个包含两个“!”的语句 围绕一个字符串。(例如:大家好!这是一个测试!再见。)我要抓住两个感叹号内的字符串,然后一个字母一个字母地反向打印。 我已经能够找到包含该语句的起点和终点,但是我很难创建一个索引,该索引将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
解决方案
解释我们使用正则表达式来查找模式,然后我们循环每次出现,并用反转的字符串替换出现。我们可以在 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
推荐阅读
- powershell - 当自动重置为真时,System.Timers.Timer 每天漂移 1 秒
- machine-learning - 如何使用给出图像数据集的数据集训练模型,并在单独的 csv 文件中给出图像的标签?
- html - 如何在 iframe 中禁用此视频的自动播放?
- amazon-web-services - Jenkins:使用 AWS CLI 命令运行 Windows Powershell 脚本的问题
- zsh - 启用 Oh-My-Zsh 时启动 zsh 很慢
- excel - 根据列中的 ID 值选择最大值的函数
- facebook - 浏览器插件如何在没有选择加入的情况下获取 Facebook 中的群组成员详细信息?
- javascript - jsTree排序函数回收
- php - 如何在 Wordpress 上的帖子标题后添加内容?仅在帖子标题上
- visual-studio-2019 - Visual Studio 2019 16.6.1 缓慢且无响应