If len(list) is not divisible by 3, then exclude last item in a function . Python 2.7.1
-
26-02-2021 - |
Frage
if you have a string
string='abcdefg'
and you wanted to check if the length of the string is divisible by 3
len(string)
what command would you use?
Lösung
You can use the modulo (division remainder) operator %
:
if len(s) % 3 == 0:
...
If you want to strip the string to a length divisible by 3, use
s[:len(s) // 3 * 3]
or
s[:-(len(s) % 3)]
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow