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)


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:
i] = 'hello' # accessing element IN THE LIST as index/position i, reassigning it to the new value 'hello'
i += 1

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

Your email address will not be published. Required fields are marked *