[英]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])
How do I make this print out the greeting, excluding the outside letter "h", but leaving the inside letter "h" where it is.我如何打印出问候语,不包括外部字母“h”,但将内部字母“h”保留在原处。
I need the output to be:我需要 output 为:
"Hello How Are You, What?"
"W ,uoY erA woH olle"
With my current code output is:我当前的代码 output 是:
"Hello How Are You, What?"
"?tahW ,uoY erA woH olle"
I just need the '?tah" to be gone.我只需要'?tah' 消失。
greeting = "hello how are you, what?"
title = greeting.title()
print(title)
print(title[greeting.rfind('h') - 1:greeting.find('h'):-1])
This outputs:这输出:
Hello How Are You, What?
W ,uoY erA woH olle
Demo: https://replit.com/@blhsing/UnknownMustyFlatassembler演示: https://replit.com/@blhsing/UnknownMustyFlatassembler
Regular expressions would be another way to achieve this.正则表达式是实现这一目标的另一种方式。
>>> import re
>>> greeting = "hello how are you, what?"
>>> re.sub(r'^[hH](.*)[hH].*?$', r'\1', greeting.title())[::-1]
'W ,uoY erA woH olle'
We're going to match everything between either h
or H
and the last h
or H
in the string and replace the whole string with just that, then reverse it with [::-1]
.我们将匹配字符串中h
或H
与最后一个h
或H
之间的所有内容,并用它替换整个字符串,然后用[::-1]
反转它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.