简体   繁体   中英

Why does a syntax error happen in my code?

The string method I want to use:

s.count(sub[, start[, end]])

A syntax error occurs at the first comma.

An error occurs at the first comma, so I checked several times if all the '[' signs or the ')' signs are used as a set(as in 'closed').

s = input("Enter a sentence that contains at least 4 words: ")

print("c) ", ljust(s, 50, fillchar='/'))
print("d)", s.count('oh'[, 1[, 5]]))
print("e)", s.index('oh'[, 1[, 5]]))

The first comma inside the count method shows an invalid syntax error. Just for your reference, I attached the line before and after the erroneous code, as well. Is there a parentheses that is not closed, or are there any errors besides the one I have thought about?

You're misreading the syntax of s.count .

s.count(sub[, start[, end]])

What that means is that you call count with the substring, optionally followed by a starting position (the [, start portion), and if that optional start position is provided it can be followed by an optional end (the [, end portion). The two ]] at the end before the closing parenthesis are the closures for the two optional portions.

What all that means is that you can call count in any of these three ways:

  • By passing a substring only

    s.count(sub)
  • By passing a substring and the place to start

    s.count(sub, 5)
  • By passing a substring, the place to start, and the place to stop

    s.count(sub, 5, 15)

(BTW, you're going to have the same issue for the same reason with s.index on the next line once you correct this one.)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM