Learn Python Programming

Strings and Characters


Strings are the immutable data type in Python. A string is a group of characters. Strings are very important because most of the data that we use in daily life will be in the form of strings.

For example – the names of person, their address, their office addresses, their bank details, their vehicles number etc. are all strings.

In Python, a string is denoted by str datatype. Python handles strings and characters in the same manner, as there is no separate datatype to represent individual character in python.

How to create a string in python?

A string in python can be created by assigning a group of characters together to any variable. And this group of characters should be enclosed within single quotes(”) or double quotes(“”).

Example:

str1 = 'Welcome to the Share Query, Learn Python Programming!'
str2 = "Welcome to the Share Query, Learn Python Programming!"

Sometimes we do use triple single quotes(”’) or double quotes(“””) in order to show a string of several lines.

str3 = '''Welcome to the Share Query, Learn Python Programming!
and practice examples of each topics. You can find all python topics and examples related to that topic. Also you can explore more programming language tutorial on Share Query.'''

str3 = """Welcome to the Share Query, Learn Python Programming!
and practice examples of each topics. You can find all python topics and examples related to that topic. Also you can explore more programming language tutorial on Share Query."""

Sometimes you need to show a sub string inside a string. This can be achieved as given below:

str1 = 'Welcome to the "Share Query"'
str1 = "Welcome to the 'Share Query'"

Escape Characters and their Meanings

Escape CharactersMeanings
\aBell or alert
\bBackspace
\nNew Line
\tHorizontal tab space
\vVertical tab space
\rEnter Button
\xCharacter x
\ \Displays single \

Raw String

In order to nullify the effect of escape characters, you can create a raw string by adding ‘r’ before the string. Raw strings take escape characters like \t or \n etc. as ordinary characters in a string and display the string with escape string in it.

str1 = r"Welcome to the \nShare Query\nTutorial"

#Output
Welcome to the \nShare Query\nTutorial

How to calculate length of a String?

A string length is measured by the number of characters in it. In python, there is len() function to find out the length of a string. len() function returns the number of characters including spaces in a string.

str1 = 'Python Tutorial - Strings and Characters'
print(len(str1))

#Output
40

Indexing in Strings

Index represents position of an individual character or elements in a string. Index is written using square braces[]. By specifying the position number in a string, you can get the individual element or character of a string.

str[0] represents the 0th element in a string.
str[1] represents the 1th elements in a string.

You can use negative index number, in order to get the element or character in reverse order.

str[-1] represents the last element.
str[-2] represents the second element.

For Example

Slicing the Strings

Python allows a string slicing by specifying start and the end index in the syntax given below:

stringname[start:stop:stepsize]
  • Default step size is considered 1.
  • If ‘start’ and ‘stop’ value not provied in the slicing syntax. Then slicing is done from 0th to (n-1)th elements.
str = 'Learn Python'
print(str[0:5:1])

str = 'Learn Python'
print(str[0:5:2])

str = 'Learn Python'
print(str[::])

str = 'Learn Python'
print(str[::2])

str = 'Learn Python'
print(str[2::])

str = 'Learn Python'
print(str[:4:])

#Output
Learn
Lan
Learn Python
LanPto
arn Python
Lear

A sub string can be extracted from a string by using reverse slicing.

str = 'Learn Python'
print(str[-6::])

str = 'Learn Python'
print(str[:5:-2])

str = 'Learn Python'
print(str[:2:-2])

str = 'Learn Python'
print(str[-1::-1])

str = 'Learn Python'
print(str[-1:-4:-1])

#Output
Python
nhy
nhy r
nothyP nraeL
noh

Repeating the Strings

A string can be repeated n times by using the ‘*’ operator.

str = 'Learn Python'
print(str*2)

#Output
Learn PythonLearn Python

Also, chunk of a string can be repeated n times.

str = 'Learn Python'
sub_str = str[6::]
print(sub_str*2)

#Output
PythonPython

Concatenation of Strings

By using the concatenation operator (+) also called addition operator when used in numbers addition, can concatenate strings together.

str1 = 'Welcome to the Share Query. '
str2 = 'Learn Python'

print(str1+str2)

#Output
Welcome to the Share Query Learn Python

Checking membership

In python, we can check if a string or character exist in the another string by using the ‘in’ and ‘not in’ operators. The operators ‘in’ and ‘not in’ operators make case-sensitive comparisons. So, upper case and lower case letters or strings compared differently.

#A python program to check whether a sub string is a part of main string.

main_str    = 'This is a Python Tutorial Website.'
sub_str     = 'Python'

if sub_str in main_str:
        print(sub_str+' is found in main string.')
else:
        print(sub_str+' is not found in the main string.')

#Output
Python is found in main string.