How to Convert to a String in Python

Shares & Saves

Unlike in C++ and Java, Python variables don't contain explicit type information. If you're using a function that requires a string, you can pass variables of other types to it without throwing an exception, although your code may throw an exception when it tries to process the variable. The only data types you may need to convert to strings are compound data structures such as sets and lists. Python includes convenient functions and operators for iterating over the items in a data structure and appending characters to a string variable.

Strong, Dynamically Typed Languages

  • C++ and Java require a type reserve word to precede all variable allocations because the compiler or runtime environment must know how to treat the data. These statically typed languages use type casting to convert between types if possible. Since Python is a dynamically typed language, the interpreter infers the type at runtime, so you simply assign values to variables as needed. You can assign any data type to a variable formerly used as a different type, and the Python garbage collector removes the old variable from memory.

Converting Data Structures to Strings

  • If your program gathers text information in a compound structure such as a list, tuple or set, you can loop over the data structure to append elements to a string variable. You don't need to declare a string variable before iterating over the data structure, but it can make your code simpler. For example, the following code demonstrates the most basic method for converting a list to a string:

    ultimateQuestion = "" # declare empty string “ultimateQuestion”

    tokens = [“What's “, 6, “ times “, 9, “?”] # list of mixed types with whitespace

    for t in tokens:
    ultimateQuestion += str(t)


    The str method used in the for loop casts integers to strings and has no effect on existing strings. If you run this code in the Python interpreter, it prints out “What's 6 times 9?”

Built-In String Methods

  • Like most high-level languages, Python includes many methods that belong to the built-in string type. In Python, you can call these methods from a string literal, so to concatenate list elements, for example, you can pass a list variable to a string literal's join method as in the following example:

    tokens = ['Hello', 'World'] #string tokens without whitespace

    pyString = ' '.join(tokens)


    This script calls join from the ' ' string literal, which is a one-character string of just the space character. It concatenates 'Hello' and 'World' into “Hello World” by inserting the calling object -- a space character -- between each list element.

Python Variable Scope Resolution

  • As in other high-level languages, you must pay attention to a variable's scope when declaring and assigning string variables. If you declare a string variable inside a function or loop, you can't use it anywhere else in the program. For example, the Python interpreter destroys the variable “verticalList” after returning from the loop:

    for g in groceries:

    verticalList += g + '\n'    # string declared inside for loop


    This script throws an exception because “verticalList” is not defined outside the scope of the for loop.




  • Photo Credit g-stockstudio/iStock/Getty Images

You May Also Like

Read Article

Your Black Friday/Cyber Monday Survival Guide