Skip to content

Python NoneType to string

  • by

Converting NoneType to a string is possible but the result will string 'None'. Use the boolean OR operator to convert NoneType to a string in Python, e.g. result = None or "".

my_var = None

result_1 = my_var or ''
print(result_1)  #  ""

result_2 = my_var or 'hello'
print(result_2)  #  "hello"

Python NoneType to string

Simple example code.

def convert_string(value):
    new_value = str(value)
    return new_value


res = convert_string(None)
print(res)
print(type(res))

Output:

Python NoneType to string

Condition to convert NoneType into a string

int_list = ['10', '3', None, '5', '8']
i = 0
for i in range(len(int_list)):
if int_list[i] is None:
int_list[
i] = 'hello' # accessing element IN THE LIST as index/position i, reassigning it to the new value 'hello'
i += 1
print(int_list)

Output: [’10’, ‘3’, ‘hello’, ‘5’, ‘8’]

Do comment if you have any doubts or suggestions on this Python string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading