繁体   English   中英

我如何让这行代码打印出问候语,不包括一些字符

[英]How do I have this line of code print out the greeting, excluding some characters

#This is my string known as "greeting".

greeting = "hello how are you, what?" 

#This prints the greeting the normal way.

print(greeting.title())

#This prints the greeting backwards and excluding the chosen letter "h" on the outside.  

print (greeting.title()[:greeting.find("h"):-1] + greeting[greeting.rfind("h")-1:5])

我如何打印出问候语,不包括外部字母“h”,但将内部字母“h”保留在原处。

我需要 output 为:

"Hello How Are You, What?"

"W ,uoY erA woH olle"

我当前的代码 output 是:

"Hello How Are You, What?"

"?tahW ,uoY erA woH olle"

我只需要'?tah' 消失。

greeting = "hello how are you, what?"
title = greeting.title()
print(title)
print(title[greeting.rfind('h') - 1:greeting.find('h'):-1])

这输出:

Hello How Are You, What?
W ,uoY erA woH olle

演示: https://replit.com/@blhsing/UnknownMustyFlatassembler

正则表达式是实现这一目标的另一种方式。

>>> import re
>>> greeting = "hello how are you, what?"
>>> re.sub(r'^[hH](.*)[hH].*?$', r'\1', greeting.title())[::-1]
'W ,uoY erA woH olle'

我们将匹配字符串中hH最后一个hH之间的所有内容,并用它替换整个字符串,然后用[::-1]反转它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM