Python Strings

(Sponsors) 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 doesn’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 NameMethods 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 (Sponsors)

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!

10 thoughts on “Python Strings

  1. Nidhi

    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

      1. Aero

        A few comments, though…

        IndentationError: expected an indented block

        is the error I got. I found out that
        print(i, end="")
        has to be preceded by a space or [TAB].
        Second, after entering the above line, you will have to press ENTER once more to get the output.

  2. Niko

    The example that “proves” string concatenation generates another object, while true for python, does not have to always be true. It could be an indication that there was not enough space in memory to leave the string object where it was, thus relocating the whole string.

  3. Adebayo Adebayo

    I am trying to write a python function that takes in two strings and return a list that contains elements from the two string and delete consecutive duplicate occurences of a character and their other instances fro the two strings:

    string_one = “need”
    string_two = “near”

    result = [ ‘a’, ‘d’, ‘n’, ‘r,]

    Note that all instances of element ‘e’ are removed. Any help is appreciated. Thanks a lot.

    1. PythonGuru

      You can use set type to easily accomplish this as follows:

      >>> string_one = “need”
      >>> string_two = “near”
      >>> string_one + string_two
      >>> set(string_one + string_two)
      {‘e’, ‘d’, ‘r’, ‘a’, ‘n’}
      >>> list(set(string_one + string_two))
      [‘e’, ‘d’, ‘r’, ‘a’, ‘n’]

  4. Mahesh

    str = “Welcome”
    str[1:-1] –> O/P is “Welcom”
    str[-1] –> O/P is “e”
    then why str[1:-1] does not consider “e” in it’s output?

    1. PythonGuru

      When you say str[-1] you are asking Python to return the last element from the right.

      On the other hand, when you say str[1:-1], Python returns a slice of string from the offsets 1 to -1, not including the string at offset -1


Leave a Reply

Your email address will not be published. Required fields are marked *