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?

War es hilfreich?

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
scroll top