Categories: python

Strings in Python

  • A Python string is a collection of characters enclosed by single, double, or triple quotes.
  • The string is an immutable sequence data type.
  • The computer does not understand the characters; instead, it stores the manipulated character as a combination of 0’s and 1’s internally.
  • Each character is encoded in either ASCII or Unicode. As a result, Python strings can also be referred to as a collection of Unicode characters.
  • Python doesn’t support the character data type; instead, a single character written as ‘p’ is treated as the string of length 1.
Creating a String :

We can make a string by enclosing the characters in single or double quotation marks. Python also supports triple quotes to represent strings, but they are typically used for multiline strings or docstrings.

For instance,

str1='This is a string in Python' 
print(str1)

str2="""This is
the 
Multi-line
string."""
print(str2)

str3='Welcome to "Python Tutorial" on Coderzpy.com'
print(str3)

Output:

This is a string in Python
This is
the 
Multi-line
string.Welcome to "Python Tutorial" on Coderzpy.com
String indexing:

Individual characters of a String can be accessed in Python using the Indexing method. Indexing enables negative address references to access characters from the String’s back end, for example, -1 refers to the last character, -2 refers to the second last character, and so on.

Example:

str=”Coderzpy”

CharactersCoderzpy
Forward Index01234567
Backward Index-8-7-6-5-4-3-2-1
String slicing:

The slicing method is used to access a range of characters in the String. A Slicing operator is used to slice a String (colon).

Syntax:

string_name[starting_index : finishing_index]
  • String_name is the name of the variable holding the string.
  • starting_index is the index of the beginning character which you want in your sub-string.
  • finishing_index is one more than the index of the last character that you want in your substring.

Example:

# Given String  
str = "CHARACTERS"  
# Start Oth index to end  
print(str[0:])  
# Starts 1th index to 4th index  
print(str[1:5])  
# Starts 2nd index to 3rd index  
print(str[2:4])  
# Starts 0th to 2nd index  
print(str[:3])  
#Starts 4th to 6th index  
print(str[4:7])  

Output:

CHARACTERS
HARA
AR
CHA
ACT

Note: In Python, the Update or deletion of characters from a String is not allowed.

Deleting the Entire String:

The del keyword can be used to delete the entire string. Furthermore, attempting to print the string will result in an error because String has been deleted and is no longer available for printing.

For instance,


String1 = "CHaracters"
print("Initial String: ")
print(String1)

# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)

Output:

Initial String: 
CHaracters
Deleting entire String: Traceback (most recent call last):
File "<string>", line 10, in <module>
NameError: name 'String1' is not defined
String Operators:

Arithmetic operators, do not operate on strings. There are, however, string processing operators.

OperatorDescriptionExample
+Appends the second string to the first>>> a=’hello’
>>> b=’world’
>>> a+b
‘helloworld’
*Concatenates multiple copies of the same string>>> a=’hello’
>>> a*3
‘hellohellohello’
[]Returns the character at the given index>>> a = ‘Python’
>>> a[2]
t
[ : ]Fetches the characters in the range specified by two index operands separated by the : symbol>>> a = ‘Python’
>>> a[0:2]
‘Py’
inReturns true if a character exists in the given string>>> a = ‘Python’
>>> ‘x’ in a
False
>>> ‘y’ in a
True
>>> ‘p’ in a
False
not inReturns true if a character does not exist in the given string>>> a = ‘Python’
>>> ‘x’ not in a
True
>>> ‘y’ not in a
False
Escape Sequences:

The escape character is used to call up a different implementation of the next character in a sequence. Backslash \ is used as an escape character in Python. To insert a character into a string, use a backslash character followed by the character you want to insert.

The following table lists escape sequences in Python.

Escape sequenceDescriptionExample
\\Backslash>>> “Hello\\Hi”
Hello\Hi
\bBackspace>>> “ab\bc”
ac
\fForm feed
\nNewline>>> “hello\nworld”
Hello
world
\nnnOctal notation, where n is in the range 0-7>>> ‘\101’
A
\tTab>>> ‘Hello\tPython’
Hello    Python
\xnnHexadecimal notation, where n is in the range 0-9, a-f, or A-F>>> ‘\x48\x69’
Hi
\onnOctal notation, where n is in the range 0-9>>> “\110\151”
Hi

Note: also read about Armstrong Number in C++Data Types in Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago