Python Program to create a String object


In Python, we can create a string object using Python's inbuilt function str() and also by assigning a sequence of characters to a variable. The sequence of characters is enclosed in the single quote or double quotes. We can also create a multiline string object using triple quotes. In this article, we look at the various ways in which we can create a string object in Python.

Example 1:Creating a string object using single quote

We can create a string object by simply assigning a sequence of characters enclosed in a single quote to a variable.

my_string = 'Hello World!'
print(my_string)

Output

Hello World!

Example 2: Creating a string object using double quote

We can create a string object by enclosing a sequence of characters in double quotes and assigning it to a variable.

my_string = "Hello World!"
print(my_string)

Output

Hello World!

Example 3: Creating a multiline string object using triple quotes

In Python we can create a multiline string object by enclosing the multiline string in a triple quote or double triple quote.

my_string = '''This is a multiline
String'''
print(my_string)

Output

This is a multiline
String

Example 4: Creating a string object using str() function

The str() function can be used to convert any data type object to a string object. In the below example, we convert an integer data type to a string using the str() function and assign it to a variable.

my_number = 123
my_string = str(my_number)
print(my_string)

Output

123

Conclusion

In Python, we can create string objects using the single quote, double quote, and triple quote to double triple quote. A triple quote is used to create a multiline string object. Python also provides the str() function to convert any datatype object to a string object. In this article, we understood all the ways in which string objects can be created in Python.

Updated on: 17-Apr-2023

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements