Is there one way to say this?

Pretty simple, maybe for someone. Is there any way to say this in one line of code?

if word.startswith('^') or word.startswith('@'): truth = True else: truth = False 
+4
source share
4 answers

I think this will be the shortest:

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

From the 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. 
+10
source

A word.startswith('^') or word.startswith('@') expression ( word.startswith('^') or word.startswith('@') ) returns a boolean value that can then be assigned to a variable, therefore:

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

excellent.

+8
source

Try:

 truth = word.startswith('^') or word.startswith('@') 
+3
source

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

This will do the job very quickly (without calling the method), but is limited to single-byte prefixes and sets truth value of word , if word is '' , None , 0 , etc. And that would / should be thrown out in a code review of more than minimal stringency.

+1
source

Source: https://habr.com/ru/post/1384607/


All Articles