Strings in Python – The Complete Reference

Strings In Python

Strings in Python are amongst the widely used data types and are created by enclosing characters in quotes. For example:

string1 = "Hello"
string2 = "welcome"

Strings are enclosed within single quotes or double-quotes. Both of these are considered as strings by the interpreter.

Python does not support the ‘character’ datatype but support strings of length one. For example:

var char1 = "H"

How to create strings in Python?

There are 3 different methods that can be used to create a string object in Python.

1. Using single quotes

Strings may be created by enclosing characters within single quotes.
For example :

var example = 'Welcome to the tutorial!'

2. Using double quotes

Strings are often created by enclosing characters within double-quotes.
For example:

var example = "Welcome to the tutorial!"

3. Using triple quotes

Strings can be created using triple quotes. By triple quotes, the strings may constitute three single-quotes or three double-quotes. It allows the user to declare multiline strings.

Additionally, triple quotes are accustomed to comment out sections of code that are ignored by the interpreter while executing the code.

var example = '''Welcome to the tutorial!'''

var example2 = """Welcome to the tutorial"""

# multi-line comment
''' This is the comment section.
The interpreter will ignore this section'''

Accessing and Manipulating Strings in Python

Indexes In String
Indexes In String

While we now know the way to make strings, we also must understand how we will access and work with the strings for our programming needs. Let’s understand the fundamentals of how you’ll be able to access a string index.

In Python, the characters of a String may be accessed by indexing. The location of the character required is specified within square brackets where the index 0 marks the first character of the string (as shown in the above image):

var1 = 'Hello World!'
print("var1[0]: ", var1[0])

The output of the above code is:

var1[0]:  H

Indexing allows negative address references to access characters from the end of the String, e.g. -1 refers to the last character, -5 refers to the fifth last character, and so on.

For example:

var1 = 'Hello World'
print("var1[-1]: ", var1[-1])
print("var1[-5]: ", var1[-5])

The output of the above code is:

var1[-1]: d
var1[-1]: W

While accessing an index out of the range will cause an IndexError. This may be illustrated with the example shown below:

var1 = 'Hello'
print(var1[5])  # gives error

Note: Only Integers are allowed to be passed as an index.
Any other data type will cause a TypeError.

1. Python String Slicing

To access a range of characters from a string, Slicing in a String is done by employing a slicing operator (colon).

Str1 = "AskPython Strings Tutorial"
print(Str1[10:20]) 

print("\nSlicing characters from 3rd to 5th character: ") 
print(String1[3:5]) 

The output of the code is as follows:

Strings Tu

Slicing characters from 3rd to 5th character: 
Py

We have a comprehensive article on Python string slicing if you’re interested in understanding this in further detail.

2. String Concatenation

Strings is concatenated using the “+” operator. The illustration of the same is shown below:

var1 = "Hi,"
var2 = "Good Morning!"
var3 = var1 + var2
print(var3)

The output of the above code snippet is as shown below:

Hi,Good Morning!

3. Updating Strings in Python

Strings are immutable, hence updation or deletion of characters isn’t possible. This can cause an error because the item assignment (case of updation) or item deletion from a String isn’t supported.

String1 = "Hello"
  
# Updating character 
String1[2] = 'p'
print("\nUpdating character at 2nd Index: ") 
print(String1) 

The output of the above code snippet is as follows:

Traceback (most recent call last):
File “/Desktop/trial.py”, line 4, in
String1[2] = ‘p’
TypeError: ‘str’ object does not support item assignment

However, the deletion of the entire String is feasible with the use of a built-in del keyword.

String1 = "hello"
del(String1)

Strings may also be updated as shown below:

# Updating entire string
String1 = "Hello"
print(String1)     # prints Hello

String1 = "Welcome"
print(String1)     # prints Welcome

# concatenation and slicing to update string
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
# prints Hello Python!

4. Repeating Strings

Strings may be repeated by using the asterisk (*) operator as follows:

var1 = "hello"
print(var1*2)    

The output of the above code is that it prints the string twice.

hello hello

5. Formatting Strings in Python

Method 1: Using the formatting operator

The string format operator % is unique to strings and behaves similar to C’s printf() family of formatting options.

print("%s has Rs %d with her" % ('Aisha', 100))

The output of the above code is:

Aisha has Rs 100 with her

Method 2: Using format() method
The format() method for strings contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order.

Str1 = "{} {}".format('Hi, It is', '2020')
print(Str1)

The output of the above code snippet is as shown below:

Hi, It is 2020

The format() method in Python can be used to format integers by allowing conversions from decimal format to binary, octal, and hexadecimal.

num = int(input())
ar1 = "{0:b}".format(num) 
print("\nBinary representation of ",num," is ", ar1)

Conclusion

And that brings us to the end of the tutorial. I hope you have a very solid understanding of Strings and their functions. We cover a lot of articles on Python OOPs and demonstrate some really interesting Python programming examples here.

References

https://docs.python.org/2/library/string.html