#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.
I need the output to be:
"Hello How Are You, What?"
"W ,uoY erA woH olle"
With my current code output is:
"Hello How Are You, What?"
"?tahW ,uoY erA woH olle"
I just need the '?tah" to be gone.
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
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]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.