Python String

Strings are used to represent text, a combination of characters, without mattering the type of characters. Therefore, strings can also store a value that contains numbers.

But the question is, how can we identify whether the value is of string (str) type or not ?
The answer is: anything enclosed within a single or double quotes, is a string. For example:

x = 'codescracker'
print(type(x))

x = 'Python is Fun'
print(type(x))

x = "134"
print(type(x))

x = '243.554'
print(type(x))

x = 'Python@134'
print(type(x))

The output is:

<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

Note - The type() function is used to find the type of a value/variable.

Strings are contiguous set of characters enclosed within a single/double quotation marks.

How to Assign a String in Python ?

To assign a string in Python, follow the program given below:

a = 'Welcome to codescracker.com'
b = "Python is Fun!"

How to Assign a Multiline String in Python ?

Sometime we need to use a large string value that expands in multiple lines. Therefore to assign a multiline string, we need to enclose the string in three single or double quotes. For example:

a = '''This is Lukas.
I'm from Berlin.
I studied in Ludwig Maximilian University of Munich.
I am Data Science Enthusiast.'''

print(a)

The output is shown in the snapshot given below:

python string

If you place some space before the string, available in line, other than the variable's line. Then the space will get considered as part of the string. For example:

a = """Hey,
    Python is fun.
  Is not it?"""

print(a)

The output is:

Hey,
    Python is fun.
  Is not it?

Access Elements (Characters) of a String in Python

Characters of a string can be accessed using their index numbers. Therefore just like list, string is also an iterable object. The syntax to access an element or character of a string in Python, is:

x[index]

where x refers to the string, and index refers to the index number of the character or element, that needs to be accessed. For example:

x = "Python is easy to learn"

print(x[0])
print(x[1])
print(x[2])

The output is:

P
y
t

Access Elements of a String from Last - Negative Indexing

An element of a string can also be accessed using of course negative indexing. The x[-1] refers to the last character of string x. For example:

x = "Python is easy to learn"

print(x[-1])
print(x[-2])
print(x[-3])

The output is:

n
r
a

The last element can also be accessed using:

print(x[len(x)-1])

The len() function returns the length of x. But it is not recommended to use above code, to access the last character of string. Better to go with print(x[-1]).

Iterate String using for Loop in Python

The string can also be iterated, using for loop. For example:

mystr = "Python Robust"

for c in mystr:
    print(c)

The output is:

P
y
t
h
o
n
 
R
o
b
u
s
t

To print all the characters of a string in single line, while iterating using for loop, replace the following statement from above program:

print(c)

with the statement, given below:

print(c, end="")

Now the output is:

Python Robust

Note - The end= parameter skips the insertion of an automatic newline after each print().

Python String Length

The len() function is used to get the length of a string. For example:

print("Enter a String: ", end="")
x = input()

print("\nLength =", len(x))

The snapshot given below shows the sample run of above program, with user input I'm from Berlin as string:

python string length

Python String Splitting/Slicing

The following program and its output, demonstrates how the string gets split in Python:

x = "Python is Awesome!"

print(x[0])
print(x[1:5])
print(x[1:6])
print(x[0:6])
print(x[7:])

The output is:

P
ytho
ython
Python
is Awesome!

While splitting the string in Python, using:

string[indexStart:indexStop]

The indexStart is included, whereas the indexStop is excluded.

Python Escape Sequence Characters

The following table briefly describes escape sequence characters used in Python:

Escape Character Code Used to/for
\\ Print one backslash
\' Print a single quote
\" Print a double quote
\b Move the cursor one space back
\a Alert the Bell
\cx Control-x
\b Backspace
\C-x Control-x
\f Form feed
\e Escape
\M-\C-x Meta-Control-x
\r Carriage return
\n Newline
\nnn Octal notation
\s Space
\x x
\t Tab
\v Vertical tab
\xnn Hexadecimal notation

Python Escape Sequence Characters Example

Here is an example program uses some of the escape sequence characters in Python.

print("\t\t\tPython String")
print("\t\t\t \\ \\ \\ \\ \\ \\ \\")
print("\t\t\t\tby")
print("\t\t\tcodescracker.com")
print("\t\t\t \\ \\ \\ \\ \\ \\ \\")
print("\nThanks to all Python programmer,")
print("who are visiting \"codescracker.com\" to improve the skill.")

The snapshot given below shows the sample output produced by above program, demonstrating the use of escape sequence characters in Python:

python escape sequence characters example

Repeat a String for n Number of Times in Python

To repeat a string for n number of times, just multiply the string with the value of n like multiply with 2 to repeat the string for two times, with 3 to repeat the string for three times. For example:

print("Enter the String: ", end="")
x = input()
print("Enter the Number of times to Repeat: ", end="")
t = int(input())

x = x*t
print("\nNow the String is:")
print(x)

The sample run with user input codescracker as string, 5 as number of times to repeat codescracker, is shown in the snapshot given below:

python repeat string for n times

Python String Methods

The pre-defined or built-in methods used to handle the string in Python are:

  • str() - converts a value to a string.
  • join() - joins all items of an iterable into a string.
  • format() - formats the string.
  • split() - splits a string into a list.
  • replace() - replaces old phrase with new, in a string.
  • index() - returns first occurrence of a specified value in a string.
  • count() - returns the number of occurrence of a specified phrase in a string.
  • reversed() - returns the reversed string object of given string.

Python String Programs

Here are the list of some recommended programs related to string in Python.

Python Online Test


« Previous Tutorial Next Tutorial »