Python String


Python String

Python String is an immutable sequence of unicode characters.

In Python, str class handles string objects, and strings are of type str.

To define a string literal, you can use single quotes, double quotes or triple quoted.

str1 = 'hello world!' #single quotes
str2 = "hello world!" #double quotes
str3 = """hello world!""" #triple quoted with double quotes
str4 = '''hello world!''' #triple quoted with single quotes

Triple quoted strings can define multiple line strings.

str1 = '''hello world!
hello user!
hello!'''

Python str type

We already know that strings are of type str in Python. Let us check that programmatically using type().

Python Program

greeting = 'hello world!'
print(type(greeting))

Output

<class 'str'>

str() built-in function

str() is a builtin function to define or convert other type objects to string.

Refer str() built-in function tutorial.

Initialize a variable with string value

In the above examples, we have done the assignment of string literal to variable. This is how strings are generally initialized in Python. You may also use str() builtin function to define a string or convert another datatype to string.

Python Program

greeting = str('hello world!')
print(greeting)

Output

hello world!

Convert any object to string

To convert objects of other datatype to string, you can use str() function.

In the following example, we are converting a floating point number to string.

Python Program

n = 25.95236
str1 = str(n)
print(str1)

Output

25.95236

Similarly, you can use str() function to convert another datatype to string.

String is a sequence of characters

Python string is a sequence of items (characters). You can use for loop to traverse through each of the character.

In the following example, we will use Python For Loop to iterate over the characters of string.

Python Program

str1 = 'hello'
for char in str1:
    print(char)

Output

h
e
l
l
o

Python String Operations

You can perform many operations on Strings in Python.

Refer Python String Operations for the list of tutorials that cover different methods and scenarios working with strings, like slicing, searching, concatenation, etc.

Python String Methods

In Python, the str class provides built-in methods that can be called on string objects.

Summary

In this tutorial of Python Examples, we learned about Python Strings, how to define or initialize them, how str() function can be used, different python string operations that can be done in Python, etc.