The return statement returns extra apostrophes and brackets, which I could not figure out why.
This code finds whether a substring is present in the string.
def find(the_string, search_this):
if search_this in the_string:
a = the_string.find(search_this)
# returns the unexpected
return (search_this, "found at", str(a))
else:
# the correct output I am looking for
return (search_this + " was not found at " + the_string)
print(find("qweabc","abc"))
print(find("abcd", "xyz"))
The first return statement returns me with a print statement which is not desirable.
Example: ('abc', 'found at', '3')
The second return statement returns me with a print statement which is the one I am looking for:
Example: xyz was not found at abcd
When printed out, why does the first return statement have extra brackets and apostrophes?
This expression creates a tuple
of three strings. In Python a tuple
is similar to a list:
In [138]: ('one', 'two', 'three')
Out[138]: ('one', 'two', 'three')
This expression joins three strings into one string:
In [139]: ('one'+ 'two'+ 'three')
Out[139]: 'onetwothree'
The ()
in this case a just a grouping tool, and don't make a change:
In [140]: 'one'+ 'two'+ 'three'
Out[140]: 'onetwothree'
To create a tuple
with one item, such as a string, you have to include a comma:
In [141]: ('one'+ 'two'+ 'three',)
Out[141]: ('onetwothree',)
In fact, it's the commas that create the tuple (more so than the ()
)
In [142]: 'one', 'two', 'three'
Out[142]: ('one', 'two', 'three')
and for comparison a list:
In [143]: ['one', 'two', 'three']
Out[143]: ['one', 'two', 'three']
This notation for strings, tuples, and lists can be confusing at the start, but worth learning well.
and one other variation - passing the three strings to a print
function:
In [144]: print('one', 'two', 'three')
one two three