-2

I'm new to Python and I'm messing around with this and I don't really know why when I change the brackets to parenthesis I get an error, or why I can't just use len(text - 1).

I'm looking at this code:

def reverse(text):
    result = ""
    length = len(text)
    for i in text:
        result += text[length - 1]
        length -= 1
    return result

Any help with understanding this is greatly appreciated!

Thanks!

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
Eehenhyu
  • 1
  • 1
  • You get an error because a string minus a number doesn't work – OneCricketeer Mar 09 '17 at 14:49
  • Your loop is also somewhat pointless. http://stackoverflow.com/questions/18686860/reverse-a-string-in-python-without-using-reversed-or-1 – OneCricketeer Mar 09 '17 at 14:51
  • 1
    as an aside, if you want the reverse of the string you can just use reverse slicing: "mystring"[::-1] == "gnirtsym" – Vince W. Mar 09 '17 at 14:51
  • @cricket_007: Eehenhyu appears to be a beginner that is learning by poking at some existing code (perhaps from a tutorial?). The goal doesn't seem so much to be how to reverse a string, but how to understand the Python represented in this example. (Note: I'm not saying it's a good question. I'm just saying you're missing the point of why it was asked.) – Steven Rumbalski Mar 09 '17 at 14:56
  • instead of `len(text - 1)` use `len(text) - 1` – Boern Mar 09 '17 at 15:30

5 Answers5

1

When you use len(text - 1) you try to subtract int (1) from str (text). It is insupported operation in python (and moreover, impossible). To get a part of string you need you must use text[length - 1].

Dmitry
  • 2,026
  • 1
  • 18
  • 22
1

You can't use text - 1 because that doesn't make sense; you cannot take 1 from a string.

Now, as for len(...) this is a function so has () for the call rather than []. You pass it the thing you want the length of.

text[length - 1] is indexing into the string, at a position, and follows the list syntax for indexing or sub-scripting.

doctorlove
  • 18,872
  • 2
  • 46
  • 62
1

Python Parentheses

Parentheses play many different roles in Python these are some of the main roles they play:

The mathematical role:

Python parentheses act like parentheses in math as they are at the top of the Python Priority Precedence

This means that this:

>>> 3 + 4 * 2

returns:

12

Whereas with parentheses:

>>> (3 + 4) * 2

returns:

14

But that's not all, their priority also expands to Boolean expressions:

for example:

False and False or True and True

evaluates to True as and is executed before or. However, if you add some parentheses:

False and (False or True) and True

It evaluates to False as the or is executed before the and

Tuple

In python, when you put something in a tuple you use () notation.

Functions

When you declare or call a function you always need to add the parentheses after the function name. Think of them as a basket to put the arguments in. If you forget them the Python interpreter will think that you are calling a variable for example:

list

This is a variable called list and does nothing special

list() #Empty basket

This, however, is a call to a function as there is a "basket"

Square Brackets

Square Brackets also have quite a few roles:

Lists

In python, you use square brackets if you want to declare a list instead of a tuple.

List comprehension

List comprehension is actually pretty complicated so read this for more information but just know that it uses square brackets

Looking up

The main use of square brackets is to look up a value inside a list, tuple, or dictionary. Think of it like the google search bar: you write what you want and it tells you what it has. For example:

tuple = (2, 4)

if you want to get 4 you will need to look up the 2nd value of the tuple:

tuple[1] #The first value is 0

Slicing

Slicing is simply the idea of taking only certain parts of a list (or tuple, dictionary or even string). Here is an explanation by Greg Hewgill (https://stackoverflow.com/a/509295/7541446):

There is also the step value, which can be used with any of the above:

a[start:end:step] # start through not past end, by step

The key point to remember is that the :end value represents the first value that is not in the selected slice. So, the difference beween end and start is the number of elements selected (if step is 1, the default).

The other feature is that start or end may be a negative number, which means it counts from the end of the array instead of the beginning. So:

a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items

Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

I hope this provided useful insight to explaining the difference between parentheses and square brackets.

This means that in your question len() is a function where you are putting text inside the basket. However, when you call text[length-1] you are looking up the value at position length-1

Community
  • 1
  • 1
Joseph Chotard
  • 666
  • 5
  • 15
  • 1
    The tutorialspoint.com link for tuples shows some lines ending with superfluous semicolons. Perhaps you could find a link that doesn't foist such unneeded visual abominations on unsuspecting learners? Also, the only time parenthesis are required to create a tuple is for empty tuples, otherwise they are optional (but it's often good style to use them). It's really the comma that's doing the work of making something a tuple. – Steven Rumbalski Mar 09 '17 at 16:31
0

The python builtin function len() returns the length in numbers of the object in argument e.g

temp = [1, 2, 3, 4]
length = len(temp)

then the len() will return 4 in this case. but if someone write

length = len(temp-1)

then

temp-1

is not a valid object, therefor you cannot use it.

SHAHS
  • 462
  • 1
  • 5
  • 13
0

The reason you can't do len(text-1) is because text is a string type you are trying to reverse, and being a string you cannot combine it with numbers(unless they are a string, but thats a different story) without getting an error. Therefore you do len(text)-1 because len(text) would equal the length of whatever the text is(lets say four), and then you can subtract 1 from 4 because 4 is an integer.

The reason you need brackets and not parentheses when you are doing text[length-1] is because in python trying to get a single value out of a string requires the use of string[] and putting a position in the string inside the []. You use partakes to call functions like print(string) or len(text), so putting text(length-1) would create an error that basically says the program doesn't have a function named "text" and it doesn't know what to do.

Hope this helps. Tell me if you have any more questions.

Jacob Green
  • 61
  • 1
  • 10