Search code examples
pythonprintingformat-specifiers

Printing using %s


enter image description here

I tried to print a list using format specifier %s in PYTHON. I thought %s will take only the string value from the list. Why did it take even int and float too. Can someone please explain?Is there any method we can extract just the float, int and string values from a heterogenous list separately?

Thank you in advance


Solution

  • Instead of using a format specifier, why don't you just loop through each element in the list and check to see whether it is a string. Here are two ways you could do that

    listData = [10, 'Hello', 50.3]
    stringData = [item for item in listData if isinstance(item, str)]
    for string in stringData:
        print(string)
    

    This uses the isinstance() function to check whether each element in the list is a string, and then appends it to a list of strings to be printed later. This can also be done using the type() function.

    listData = [10, 'Hello', 50.3]
    stringData = [item for item in listData if type(item) == str]
    for string in stringData:
        print(string)