Thursday, February 6, 2020

Strings in Python With Method Examples

String which represents a sequence of characters is one of the most used type in most of the applications. So programming languages generally ensure that String is well optimized and has an extensive API with methods to cover most of the String operations. Python is no different and String in Python has also many optimization features and lots of methods.

Python String

String in Python is of type “str” which means every String literal created is an object of str class. strings in Python are arrays of bytes representing unicode characters.

For characters there is no separate data type in Python, a single character is also string of length 1.


Creating a String in Python

You can create a String in Python by enclosing a group of characters in either single quotes or double quotes.

Both of the following are valid and work in similar way-

s = 'Hello'

s = "Hello"

You can also create String in Python using tripe single quotes or triple double quotes. This way of creating String is useful if you have a multiline String.

s = '''This tutorial on String in Python gives examples of 
creating strings, string optimizatin features and examples
of functions in String.'''

print(s)

Output

This tutorial on String in Python gives examples of 
creating strings, string optimizatin features and examples
of functions in String.

Showing quotes as part of String in Python

If you have to show quotes as part of string then you can use another type of quote to enclose string and the quote which has to be part of string in the inner string.

For example if you have to show text – This isn’t part of the original deal
then use double quotes to enclose the String and single quote as part of the text.

s = "This isn't part of the deal"
print(s)

Output

This isn't part of the deal

If you have to show text- He said “May I come in”
then use single quotes to enclose the String and double quotes as part of the text.

s = 'He said "May I come in"'
print(s)

Output

He said "May I come in"

Escape characters in a String

You can also use escape characters with a String in Python.

Some of the escape characters that can be used in Strings are-

Escape character Description
\aBell or alert
\bBackspace
\nNew line
\rCarriage return (enter)
\sSpace
\tHorizontal tab space
\vVertical tab space

For example-

s = "This text has \t spaces and goes to \n next line"
print(s)

Output

This text has   spaces and goes to 
 next line

Backslash (\) is also used as an escape sequence in Python. If you want double or single quote with in a String then you can also put a backslash followed by a quote (\" or \').

s = "He said \"this looks good\" to his colleague"
print(s)

Output

He said "this looks good" to his colleague

Since backslash is used as an escape sequence so you’d need two backslashes (\\) if you have to display backslash as part of String. One for displaying and another as escape sequence.

print("C:\\Python\\")
print(s)

Output

C:\Python\

Accessing characters in String (String indexing)

Since String in Python is stored as an array so array indexing can be used to access characters of a String. Index is 0 based so first character is at index 0, second is at index 1 and so on.

In Python you can also use negative indexing. When negative number is used as index String is accessed backward so -1 refers to the last character, -2 second last and so on.

String in Python

Example to access characters of a String

s = "Hello World"
#first character
print(s[0])
#last character
print(s[10])
#last character
print(s[-1])
#first character
print(s[-11])

Output

H
d
d
H

Trying to use an index which is out of range results in IndexError. Using any other type except integer as index results in TypeError.

s = "Hello World"
#index out of range
print(s[12])

Output

    print(s[12])
IndexError: string index out of range

If you want to access a part of a String then you use slicing operator. Slicing is done using “[:]” operator.

For example if you want to access characters between index 3 and 7.

s = "Hello World"
#slicing String
print(s[3:7])

Output

lo W

For more examples of Python String slicing please refer this post- String Slicing in Python

Strings in Python are immutable

String in Python is immutable which means content of String object can’t be modified once assigned.

Trying to modify a String by updating or deleting any character results in error as Strings are immutable.

Updating String

s = "Hello World"
#changing String
s[3] = 't'

Output

    s[3] = 't'
TypeError: 'str' object does not support item assignment

Deleting character in a String

s = "Hello World"
#deleting char
del s[3]

Output

    del s[3]
TypeError: 'str' object doesn't support item deletion

Note that for immutable object though content can’t be changed but the reference can be changed. So a string object can be made to reference a new String.

s = "Hello World"
print(id(s))
s = "Hi"
print(s)
print(id(s))

Output

2976589114032
Hi
2976587746472

id function in CPython implementation returns the address of the object in memory. As you can see s starts referencing to the new memory location when a new String is assigned.

String interning in Python

String interning means that two string objects that have the same value share the same memory. If you have one string object with some value and you create second string object with the same value then the second string object shares the reference with the first string object. By interning strings memory is saved.

String interning is possible in Python as Strings are immutable so content can't be changed.

s1 = "Hello"
s2 = "Hello"
print(s1 is s2)
print(id(s1))
print(id(s2))

Output

True
1347382642256
1347382642256

In the example two string objects are created having the same value. As you can see when is operator is used to check whether both the operands refer to the same object or not true is returned.

Also id() function returns the same memory address for both the objects.

Operators used with String

Following operators are used with String in Python-

1. + operator-‘+’ operator when used with Strings in Python acts as a concatenation operator . It is used to append one string at the end of another string.

s1 = "Hello"
s2 = " World"
print(s1 + s2)

Output

Hello World

2. * operator- * operator is the repetition operator and used to repeat the string for the given number of times.

s1 = '*'
for i in range (1, 5):
    print(s1*i)

Output

*
**
***
****

3. in and not in operators- These operators are used for checking whether the given string or character is part of another String.

4. Slice operator- Slice operator ([:]) is used to access a substring with in a string. See more about Python string slicing here.

Python String methods

In this section Python String methods are compiled functionality wise.

  1. Getting String length in Python- For getting string length in Python, len() function is used. Refer String Length in Python - len() Function to see examples of len() function with strings.
  2. Checking String membership- To check if String present in another string in Python you can use membership operators ‘in’ and ‘not in’ or use find() or index() methods. Refer Check if String Present in Another String in Python to see examples of String membership checking.
  3. Comparing two Strings in Python- For comparing two Strings in Python you can use relational operators (==, <, <=, >, >=, !=). Refer Comparing Two Strings in Python to see examples of String comparison.
  4. Removing spaces from String in Python- To rempve spaces in String you can use str.lstrip(), str.rstrip() and str.strip() methods. Refer Removing Spaces From String in Python to see examples of removing spaces from string.
  5. Python count() method- If you want to count the number of occurrences of a specific substring in a string in Python then you can use count() method to do that. Refer Python count() method - Counting Substrings to see examples of count() method.
  6. Changing String case in Python- If you want to change string to lower case or upper case you can use one of the methods provided in str- str.lower(), str.upper(), str.capitalize(), str.title() to do that. Refer Changing String Case in Python to see examples of string case changing.
  7. split() Method- If you want to split a String in Python that can be done using split() method. Refer Python String split() Method to see examples of splitting a String using split() method.
  8. join() Method- If you want to join a sequence of Strings in Python that can be done using join() method. Refer Python String join() Method to see examples of join() method.
  9. str.isspace() Method- This method returns true if there are only whitespace characters in the string and there is at least one character. Refer Check String Empty or Not in Python to see example of isspace() method.
  10. isdigit() Method-The isdigit() method in Python String class is used to check if all the characters in the string are digits or not. Refer Python String isdigit() Method to see example of isdigit() method.
  11. isnumeric() Method-The isnumeric() method in Python String class is used to check if all the characters in the string are numeric characters or not. Refer Python String isnumeric() Method to see example of isnumeric() method.

That's all for this topic Strings in Python With Method Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Accessing Characters in Python String
  2. Getting Substring in Python String
  3. Python Program to Count Number of Words in a String
  4. Magic Methods in Python With Examples
  5. Nonlocal Keyword in Python With Examples

You may also like-

  1. Name Mangling in Python
  2. Operator Overloading in Python
  3. Passing Object of The Class as Parameter in Python
  4. instanceof Operator in Java
  5. Difference Between ArrayList And LinkedList in Java
  6. Semaphore in Java Concurrency
  7. Spring Setter Based Dependency Injection
  8. Transaction Management in Spring