Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Python Strings

January 17th 2020   314

Python Strings
Python Strings

Strings

  • Strings are amongst the most popular types in Python.
  • We can create them simply by enclosing characters in quotes.
  • Python treats single quotes the same as double quotes.
  • Creating strings is as simple as assigning a value to a variable.
  • Strings are immutable data types.

Note: Python does not support a character type; these are treated as strings of length one, thus also considered a substring.

Immutable

In python, the string data types are immutable. Which means a string value cannot be updated. We can verify this by trying to update a part of the string which will led us to an error.

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

Escape Character

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by

List of escape or non-printable characters that can be represented with backslash notation.

  • \a: Bell or alert
  • \b: Backspace
  • \cx: Control-x
  • \C-x: Control-x
  • \e: Escape
  • \f: Formfeed
  • \M-\C-x: Meta-Control-x
  • \n: Newline
  • \nnn: Octal notation, where n is in the range 0.7
  • \r: Carriage return
  • \s: Space
  • \t: Tab
  • \v: Vertical tab
  • \x: Character x
  • \xnn: Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

Example: How to use single quotes inside double quotes or vice versa?

String Comparision

Strings are compared from left to right

Example:

Triple Quotes

Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters. The syntax for triple quotes consists of three consecutive single (''' ''') or double quotes (""" """).

Raw Strings

Raw strings do not treat the backslash as a special character at all.

print('C:\\Users\\home')
print(r'C:\\Users\\home')

#output
'''

C:\Users\home
C:\\Users\\home

'''

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single character is simply a string with a length of 1.

Square brackets can be used to access elements of the string.

String Slicing

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the string.

Syntax:

my_string[index]

my_string[start:end]
my_string[start:]
my_string[:end]

my_string[start:end:step]
my_string[start::step]
my_string[:end:step]

Note: You can also use negative indexing.

Negative Indexing

Use negative indexes to start the slice from the end of the string:

String Length

To get the length of a string, use the len() function.

Check String

To check if a certain phrase or character is present in a string, we can use the keywords in or not in.

String Concatenation

To concatenate, or combine, two strings you can use the + operator.

Example: Merge two variables

String Format

As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are:

url = "http://{language}.wikipedia.org/"
url = url.format(language="en")
print(url)

'''
output

'http://en.wikipedia.org/'

'''

String Special Operators

Assume string variable a holds 'Hello' and variable b holds 'Python', then −

  • +: Concatenation - Adds values on either side of the operator a + b will give HelloPython
  • *: Repetition - Creates new strings, concatenating multiple copies of the same string a*2 will give -HelloHello
  • []: Slice - Gives the character from the given index a[1] will give e
  • [ : ]: Range Slice - Gives the characters from the given range a[1:4] will give ell
  • in: Membership - Returns true if a character exists in the given string H in a will give 1
  • not in: Membership - Returns true if a character does not exist in the given string M not in a will give 1
  • r/R: Raw String - Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter "r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. print r'\n' prints \n and print R'\n'prints \n
  • %: Format - Performs String formatting

String Methods

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

Note: All string methods returns new values. They do not change the original string.

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