Skontrolujte, či je premenná reťazec v Pythone
Pri práci s rôznymi dátovými typmi sa môžeme stretnúť s momentom, kedy potrebujeme otestovať dátový typ z hľadiska jeho povahy. Tento článok poskytuje spôsoby testovania premennej proti typu údajov pomocou Pythonu. Poďme diskutovať o určitých spôsoboch, ako skontrolovať, či je premenná reťazec.
Skontrolujte, či je premenná reťazec pomocou isinstance()
Toto isinstance (x, str) metódu možno použiť na testovanie, či je nejaká premenná konkrétnym dátovým typom. Zadaním druhého argumentu ako str môžeme skontrolovať, či premenná, ktorú odovzdávame, je reťazec alebo nie.
Python3
# initializing string> test_string> => 'GFG'> # printing original string> print> (> 'The original string : '> +> str> (test_string))> # using isinstance()> # Check if variable is string> res> => isinstance> (test_string,> str> )> # print result> print> (> 'Is variable a string ? : '> +> str> (res))> |
Výkon:
The original string : GFG Is variable a string ? : True
Skontrolujte, či je premenná reťazec pomocou type()
Túto úlohu je možné dosiahnuť aj pomocou typ funkcie v ktorom stačí odovzdať premennú a prirovnať ju k určitému typu.
Python3
# initializing string> test_string> => 'GFG'> # printing original string> print> (> 'The original string : '> +> str> (test_string))> # using type()> # Check if variable is string> res> => type> (test_string)> => => str> # print result> print> (> 'Is variable a string ? : '> +> str> (res))> |
Výkon:
The original string : GFG Is variable a string ? : True
Metóda 3: pomocou metódy issubclass().
postupný prístup
Inicializujte premennú test_string s hodnotou reťazca.
Vytlačte pôvodný reťazec pomocou metódy print().
Skontrolujte, či je premenná reťazec pomocou metódy issubclass() s nasledujúcimi parametrami: type() premennej a trieda str.
Výsledok priraďte premennej s názvom res.
Vytlačte výsledok pomocou metódy print().
Python3
# initializing string> test_string> => 'GFG'> # printing original string> print> (> 'The original string : '> +> str> (test_string))> # using issubclass()> # Check if variable is string> res> => issubclass> (> type> (test_string),> str> )> # print result> print> (> 'Is variable a string ? : '> +> str> (res))> |
Výkon
The original string : GFG Is variable a string ? : True
Časová zložitosť oboch metód je O(1) a potrebný pomocný priestor je tiež O(1), pretože na uloženie výsledku vytvárame iba jedinú premennú res.