user1064306
user1064306

Reputation:

Is there a one line way of saying this?

Pretty simple probably for someone. Is there a way to say this in one line of code?

if word.startswith('^') or word.startswith('@'):
    truth = True
else: 
    truth = False

Upvotes: 4

Views: 237

Answers (4)

John Machin
John Machin

Reputation: 82934

truth = word and word[0] in '^@'

This will do the job very rapidly (no method call involved) but is limited to one-byte prefixes and will set truth to the value of word if word is '', None, 0, etc. And it would/should be tossed out in a code review of more than minimal rigor.

Upvotes: 1

ovgolovin
ovgolovin

Reputation: 13410

I think this will be the shortest one:

truth = word.startswith(('^','@'))

From docs (look at the last line):

startswith(...)
    S.startswith(prefix[, start[, end]]) -> bool

    Return True if S starts with the specified prefix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    prefix can also be a tuple of strings to try.

Upvotes: 10

slugonamission
slugonamission

Reputation: 9642

The boolean expression (word.startswith('^') or word.startswith('@')) returns a boolean value, which can then be assigned to a variable, so:

truth = (word.startswith('^') or word.startswith('@'))

is perfectly valid.

Upvotes: 8

Michael
Michael

Reputation: 9068

Try:

truth = word.startswith('^') or word.startswith('@')

Upvotes: 3

Related Questions