Python Strings

The most commonly used data type in any project and in any programming language is String only. So you should aware of complete information about String data type.

What is String?

A sequence of characters within either single quotes or double quotes is considered as a String.

>>> a = 'ravi'
>>> b = "ravi"

In most of other programming languages such as C, C++, Java etc a single character within single quotes is treated as char data type value. But in Python there is no char data type. Hence it is treated as String only.

>>> x = 'a'
>>> print(type(x))

<class 'str'>

Multi-line String Literals

You can define multi-line String literals by using triple single or double quotes.

>>> x = '''Python
tutorials
by Ravi'''

You can also use triple quotes to use single quotes or double quotes as symbol inside String literal.

>>> a =  'This is ' single quote symbol'                                                ==> SyntaxError: invalid syntax
>>> b =  'This is \' single quote symbol'                                              ==> valid
>>> c =  "This is ' single quote symbol"                                              ==> valid
>>> d =  'This is " double quotes symbol'                                           ==> valid
>>> e =  'The "Python Tutorial" by 'Ravi' is very helpful'            ==> SyntaxError: invalid syntax
>>> f =  "The "Python Tutorial" by 'Ravi' is very helpful"           ==> SyntaxError: invalid syntax
>>> g =  'The \"Python Tutorial\" by \'Ravi\' is very helpful'     ==> valid
>>> h =  '''The "Python tutorial" by 'Ravi' is very helpful'''         ==> valid

Access Characters of a String

You can access characters of a string by using the following ways.

  • By using Index
  • By using Slice Operator

By using Index

Python supports both +ve and -ve indexing.

  • +ve index means left to right (Forward direction)
  • -ve index means right to left (Backward direction)

Let’s understand this using example in IDLE.

>>> x ='Python'
>>> x[0]
'P'
>>> x[4]
'o'
>>> x[-1]
'n'
>>> x[10]
Traceback (most recent call last):
    File "<pyshell#10>", line 1, in <module>
        x[10]
IndexError: string index out of range

If you are trying to access characters of a string with out of range index then you will get an error indicating – IndexError: string index out of range.

By using Slice Operator

Syntax: String[begin-index:end-index:step]

begin-index  : From where we have to consider slice(substring)
end-index     : We have to terminate the slice(substring) at endindex-1
step                : incremented value

Note: If you do not specify begin-index then it will consider from beginning of the string. If you do not specify end-index then it will consider from end of the string. The default value for step is 1.

>>>  x = "Learning Python is very very easy!!!"
>>>  x[1:7:1]
'earnin'
>>>  x[1:7]
'earnin'
>>>  x[1:7:2]
'eri'
>>>  x[:7]
'Learnin'
>>>  x[7:]
'g Python is very very easy!!!'
>>>  x[::]
'Learning Python is very very easy!!!'
>>>  x[:]
'Learning Python is very very easy!!!'
>>>  x[::-1]
'!!!ysae yrev yrev si nohtyP gninraeL'

Behaviour of Slice Operator

Syntax = string[begin:end:step]

  • Step value can be either +ve or –ve
  • If +ve then it should be forward direction (left to right) and we have to consider begin to end-1
  • If -ve then it should be backward direction (right to left) and we have to consider begin to end+1

Forward Direction

You have to remember these concepts about slicing in forward direction.

  • The default value for begin : 0
  • The default value for end : length of string
  • The default value for step : +1

Backward Direction

You must remember these concepts about slicing in backward direction.

  • The default value for begin: -1
  • The default value for end: -(length of string+1)

Mathematical Operators for String Literals

You can apply the following mathematical operators for String literals.

  • + operator for concatenation
  • * operator for repetition
>>> print("Learn "+"Python") 
Learn Python

>>> print("Ravi"*2) 
RaviRavi
  • To use + operator for Strings, it is compulsory both arguments should be str type.
  • To use * operator for Strings, it is compulsory one argument should be str and other argument should be int.

String Length

You can use len() function to print the number of characters present in the string.

>>> x = "Hello, World!"
>>> print(len(x))
13

Checking Membership in Strings

You can check whether the character or string is the member of another string or not, by using in and not in operators.

a ='Ravi'
print('v' in a) 
True
print('z' in a) 
False
print('z' not in a)
True

String Formatting

As you know very well, you cannot combine strings and numbers.

age = 26
txt = "My name is Ravi, I am " + age

Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
txt = "My name is John, I am " + age
TypeError: can only concatenate str (not "int") to str

But There is a way, you can combine strings and numbers by using the format() method. The format() method takes the passed arguments, formats it and places it in the string where you mention the placeholders {}.

age = 26
txt = "My name is Ravi, and I am {}."
print(txt.format(age))

The format() method can take unlimited number of arguments, and are placed into the respective placeholders. You can use index numbers {0} to be sure that the arguments are placed in the correct placeholders sequences.

no_quantity = 2
item_number = 462
price_commodity = 19.99
my_order = "I want {} pieces of item {} for {} dollars."
print(myorder.format(no_quantity, item_number, price_commodity))

my_order = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(no_quantity, item_number, price_commodity))

Escape Character in Strings

If you want to insert characters that are not valid in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

Let’s understand an example of an invalid character i.e double quote surrounded by double quotes inside a string.

text = "You can "learn python" easily in thecodecloud tutorials"

SyntaxError: invalid syntax

You can fix this issue by using escape character \”.

text = "You can \"learn python\" easily in thecodecloud tutorials"

You can implements below escape characters if needed.

Escape character symbol Description
\’   Single Quote
\\  Backslash
\n  New Line
\r  Carriage Return
\t  Tab
\b  Backspace

String Methods

Python contains a set of built-in methods you can use on strings.

For instance, we will remove the white spaces on both side using strip() method.

>>> s="   this is test   "
>>> s.strip()
'this is test' 

Here are few methods that are used with string literals.

Method  Description
capitalize()  To convert the first character to upper case of string
casefold()  To convert whole string into lower case
center()  It returns a centered string
count()  It returns the number of times a specified value occurs in a string
encode()  It returns an encoded version of the string
endswith()  It returns true if the string ends with the specified value
expandtabs()  It sets the tab size of the string
find()  It searches the string for a specified value and returns the position of where it was found
format()  It formats specified values in a string
format_map()  It formats specified values in a string
index()  It searches the string for a specified value and returns the position of where it was found
isalnum()  It returns True if all characters in the string are alphanumeric
isalpha()  It returns True if all characters in the string are in the alphabet
isdecimal()  It returns True if all characters in the string are decimals
isdigit()  It returns True if all characters in the string are digits
isidentifier()  It returns True if the string is an identifier
islower()  It returns True if all characters in the string are lower case
isnumeric()  It returns True if all characters in the string are numeric
isprintable()  It returns True if all characters in the string are printable
isspace()  It returns True if all characters in the string are whitespaces
istitle()  It returns True if the string follows the rules of a title
isupper()  It returns True if all characters in the string are upper case
join()  To join the elements of an iterable to the end of the string
ljust()  It returns a left justified version of the string
lower()  To convert a string into lower case
lstrip()  To remove spaces at left hand side
maketrans()  It returns a translation table to be used in translations
partition()  It returns a tuple where the string is parted into three parts
replace() It returns a string where a specified value is replaced with a specified value
rfind()  It searches the string for a specified value and returns the last position of where it was found
rindex()  It searches the string for a specified value and returns the last position of where it was found
rjust()  It returns a right justified version of the string
rpartition()  It returns a tuple where the string is parted into three parts
rsplit()  It splits the string at the specified separator, and returns a list
rstrip()  To remove spaces at right hand side
split()  It splits the string at the specified separator, and returns a list
splitlines()  It splits the string at line breaks and returns a list
startswith()  It returns true if the string starts with the specified value
strip()  To remove spaces both sides
swapcase()  lower case becomes upper case and vice versa
title()  To convert the first character of each word to upper case
translate()  Returns a translated string
upper()  To convert a string into upper case
zfill()  Fills the string with a specified number of 0 values at the beginning

Previous Read : Python Type Casting

 

Share on:

Ravindra Kumar

Hi, This is Ravindra. I am founder of TheCodeCloud. I am AWS Certified Solutions Architect Associate & Certified in Oracle Cloud as well. I am DevOps and Data Science Enthusiast.

Recommended Reading..

Leave a Comment