Zkontrolujte, zda je proměnná řetězec v Pythonu
Při práci s různými datovými typy můžeme narazit na situaci, kdy potřebujeme datový typ otestovat z hlediska jeho povahy. Tento článek poskytuje způsoby, jak otestovat proměnnou proti datovému typu pomocí Pythonu. Pojďme diskutovat o určitých způsobech, jak zkontrolovat, že proměnná je řetězec.
Zkontrolujte, zda je proměnná řetězec pomocí isinstance()
Tento isinstance (x, str) metodu lze použít k testování, zda je nějaká proměnná konkrétním datovým typem. Zadáním druhého argumentu jako str můžeme zkontrolovat, zda předávaná proměnná je řetězec nebo ne.
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ýstup:
The original string : GFG Is variable a string ? : True
Zkontrolujte, zda je proměnná řetězec pomocí type()
Tento úkol lze také splnit pomocí typ funkce ve kterém stačí předat proměnnou a přirovnat ji 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ýstup:
The original string : GFG Is variable a string ? : True
Metoda 3: pomocí metody issubclass().
postupný přístup
Inicializujte proměnnou test_string hodnotou řetězce.
Vytiskněte původní řetězec pomocí metody print().
Zkontrolujte, zda je proměnná řetězec, pomocí metody issubclass() s následujícími parametry: type() proměnné a třída str.
Výsledek přiřaďte proměnné nazvané res.
Vytiskněte výsledek pomocí metody 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ýstup
The original string : GFG Is variable a string ? : True
Časová složitost obou metod je O(1) a požadovaný pomocný prostor je také O(1), protože pro uložení výsledku vytváříme pouze jedinou proměnnou res.