Python Strings

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

Strings in python are contiguous series of characters delimited by single or double quotes. Python don’t have any separate data type for characters so they are represented as a single character string.

Creating strings

you can also use the following syntax to create strings.

Strings in python are immutable.

What this means to you is that once string is created it can’t be modified. Let’s take an example to illustrate this point.

here str1  and str2  refers to the same string object "welcome"  which is stored somewhere in memory. You can test whether str1  refers to same object as str2  using id()  function.

What is id()  : Every object in python is stored somewhere in memory. We can use id()  to get that memory address.

As both str1  and str2  points to same memory location, hence they both points to the same object.

Let’s try to modify str1 object by adding new string to it.

As you can see now str1  points to totally different memory location, this proves the point that concatenation doesn’t modify original string object instead it creates a new string object. Similarly Number (i.e int  type) is also immutable.

Operations on string

String index starts from 0 , so to access the first character in the string type:

+  operator is used to concatenate string and *  operator is a repetition operator for string.

Slicing string

You can take subset of string from original string by using [] operator  also known as slicing operator.

Syntax: s[start:end]

this will return part of the string starting from index start  to index end - 1 .

Let’s take some examples.

Some more examples.

Note: start index and end index are optional. If omitted then the default value of start  index is 0 and that of end is the last index of the string.

ord() and chr() Functions

ord() – function returns the ASCII code of the character.
chr() – function returns character represented by a ASCII number.

String Functions in Python

Function name Function Description
len() returns length of the string
max() returns character having highest ASCII value
min() returns character having lowest ASCII value

in  and not in  operators

You can use in  and not in  operators to check existence of string in another string. They are also known as membership operator.

String comparison

You can use ( > , < , <= , <= , == , !=  ) to compare two strings. Python compares string lexicographically i.e using ASCII value of the characters.

Suppose you have str1  as "Mary"  and str2  as "Mac" . The first two characters from str1  and str2 ( M  and M ) are compared. As they are equal, the second two characters are compared. Because they are also equal, the third two characters ( r  and c ) are compared. And because 'r'  has greater ASCII value than 'c' , str1  is greater than str2 .

Here are some more examples:

Iterating string using for loop

String is a sequence type and also iterable using for loop (to learn more about for loop click here).

Note: By default print()  function prints string with a newline , we change this behavior by supplying a second argument to it as follows.

Testing strings

String class in python has various inbuilt methods which allows to check for different types of strings.

Method name  Method Description
isalnum() Returns True if string is alphanumeric
isalpha() Returns True if string contains only alphabets
isdigit() Returns True if string contains only digits
isidentifier() Return True is string is valid identifier
islower() Returns True if string is in lowercase
isupper() Returns True if string is in uppercase
isspace() Returns True if string contains only whitespace


Searching for Substrings

Method Name Methods Description:
endswith(s1: str): bool Returns True if strings ends with substring s1
startswith(s1: str): bool Returns True if strings starts with substring s1
count(substring): int Returns number of occurrences of substring the string
find(s1): int Returns lowest index from where s1 starts in the string, if string not found returns -1
rfind(s1): int Returns highest index from where s1 starts in the string, if string not found returns -1

Converting Strings

Method name Method Description
capitalize(): str Returns a copy of this string with only the first character capitalized.
lower(): str Return string by converting every character to lowercase
upper(): str Return string by converting every character to uppercase
title(): str This function return string by capitalizing first letter of every word in the string
swapcase(): str Return a string in which the lowercase letter is converted to uppercase and uppercase to lowercase
replace(old, new): str This function returns new string by replacing the occurrence of old string with new string

In next chapter we will learn about python lists

Other Tutorials

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Leave a Reply

4 Comments on "Python Strings"

Notify of

Sort by:   newest | oldest | most voted
Alex Makhalane
Alex Makhalane
5 days 8 hours ago

Wow, very interesting!! Thanks.

20 days 1 hour ago

why there is nothing about split and join

6 months 16 days ago

print(“my string”, end=”\n”)
print(“my string”, end=” “)
print(“my string”, end=”foo”)

Why do all of these statements give me a syntax error