Reputation: 27
This is the task I've been given :
Program: quote_me() Function quote_me takes a string argument and returns a string that will display surrounded with added double quotes if printed check if passed string starts with a double quote ("\""), then surround string with single quotations if the passed string starts with single quote, or if doesn't start with a quotation mark, then surround with double quotations Test the function code passing string input as the argument to quote_me()
This is my code -
def quote_me(phrase):
if phrase.startswith("\""):
print('\' + phrase + \'')
if phrase.startswith('\''):
print("\" + phrase + \"")
else:
print("use quotations in your input for phrase")
quote_me("\"game\"")
output:
' + phrase + ' use quotations in your input for phrase
desired output: 'game'
I just don't know what I'm doing wrong and how I can go about fixing it. Thanks in advance.
Upvotes: 0
Views: 1390
Reputation: 5722
You've missed quotation marks in your code. Should be:
def quote_me(phrase):
if phrase.startswith("\""):
print('\'' + phrase + '\'')
if phrase.startswith('\''):
print("\"" + phrase + "\"")
else:
print("use quotations in your input for phrase")
quote_me("\"game\"")
# Output: '"game"'
Moreover, your desired output doesn't match your description for two parts.
First, your desired output seems to replace double quotes with single quotes. If you want to do replacement instead of adding quotes and you are sure the last character of your string have corresponding quotes, you might want to do this:
def quote_me(phrase):
if phrase.startswith("\""):
print('\'' + phrase[1:-1] + '\'')
if phrase.startswith('\''):
print("\"" + phrase[1:-1] + "\"")
else:
print("use quotations in your input for phrase")
quote_me("\"game\"")
# output: 'game'
Secondly, your actually print out a warning message instead of "or if doesn't start with a quotation mark, then surround with double quotations". It sounds like the problem you got just want to add proper quotes (i.e. add quotes and avoid the type of quotes which are already there). For that, you can:
def quote_me(phrase):
if phrase.startswith("\""):
print('\'' + phrase + '\'')
else:
print("\"" + phrase + "\"")
quote_me("\"game\"")
# Output: '"game"'
Upvotes: 1
Reputation: 8636
Using [] to access the 1st thing in the string makes it simpler IMO
def quote_me(phrase):
if phrase[0] == "\"":
print('dq')
print('\'', phrase[1:-1] ,'\'')
elif phrase[0] == ('\''):
print('sq')
print("\"", phrase[1:-1], "\"")
else:
print("use quotations in your input for phrase")
quote_me("\"game\"")
Upvotes: 0