Python – Create String

Create String

To create a string in Python, we can enclose the string value (sequence of characters) in single quotes, or double quotes. To create string from other datatype, we can use str() builtin function.

Create string using single quotes

Enclose the sequence of characters in single quotes.

In the following statement, we create a string using single quotes, and assign it to a variable x.

x = 'hello world'

Create string using double quotes

Enclose the sequence of characters in double quotes.

In the following statement, we create a string using double quotes, and assign it to a variable x.

x = "hello world"

Create string str() builtin function

Pass a value (of any datatype) to str() builtin function, and the function returns the string value.

In the following statement, we create a string from a number, using str() function, and assign it to variable x.

x = str(1024)

Reference – Python str() builtin function

Example

In the following program, we create strings using single quotes, double quotes, and str() builtin function.

Python Program

#create string using single quotes
x = 'apple'
print(x)

#create string using double quotes
x = "apple"
print(x)

#create string using str()
x = str(1024)
print(x)
Run

Output

apple
apple
1024

Summary

In this tutorial of Python Examples, we learned how to create string in different ways, with the help of well detailed examples.