Interesting Facts About Python strings
Last Updated :
04 Mar, 2025
Strings are one of the most commonly used data types in Python. They allow us to work with text and can be used in various tasks like processing text, handling input and output and much more. Python strings come with several interesting and useful features that make them unique and versatile.
Here are Some Interesting Facts About Python Strings
1. Strings are Immutable
Once a string is defined, it cannot be changed.
Python
a = 'Geeks'
print(a)
a[2] = 'E'
print(a)
Output:
Traceback (most recent call last):
File "/home/adda662df52071c1e472261a1249d4a1.py", line 9, in
a[2] = 'E'
TypeError: 'str' object does not support item assignment
But below code works fine.
Python
a = 'Geeks'
print(a)
a = a + 'for'
print(a)
2. Strings Can Be Concatenated Using the + Operator
We can easily combine (concatenate) strings using the + operator. This simple operation allows you to build longer strings from smaller ones, which is helpful when working with user input or constructing strings dynamically.
Python
first_name = "Krishna"
last_name = "Nand"
full_name = first_name + " " + last_name
print(full_name)
3. Strings Support String Multiplication
In Python, we can repeat a string multiple times using the * operator. String multiplication can be used to create patterns, repeat text, or perform formatting tasks easily.
Python
4. Strings Can Be Accessed with Indexes
You can access individual characters in a string by using their index. The first character has index 0, and the last character can be accessed with a negative index (-1). This allows you to quickly access and work with specific characters within a string.
Python
s = "GFG"
print(s[0])
print(s[-1])
5. Three ways to create strings
Strings in Python can be created using single quotes or double quotes or a triple quotes. The single quotes and double quotes works same for the string creation. Talking about triple quotes, these are used when we have to write a string in multiple lines and printing as it is without using any escape sequence.
Python
a = 'Geeks'
b = "for"
c = '''Geeks a portal
for geeks'''
d = '''He said, "I'm fine."'''
print(a)
print(b)
print(c)
print(d)
print(a + b + c)
OutputGeeks
for
Geeks a portal
for geeks
He said, "I'm fine."
GeeksforGeeks a portal
for geeks
6. Printing single quote or double quote on screen
We can do that in the following two ways:
- First one is to use escape character to display the additional quote.
- The second way is by using mix quote, i.e., when we want to print single quote then using double quotes as delimiters and vice-versa.
Example-
Python
print("Hi Mr Geek.")
# use of escape sequence
print("He said, \"Welcome to GeeksforGeeks\"")
print('Hey so happy to be here')
# use of mix quotes
print ('Getting Geeky, "Loving it"')
OutputHi Mr Geek.
He said, "Welcome to GeeksforGeeks"
Hey so happy to be here
Getting Geeky, "Loving it"
7. Printing escape character
If there is a requirement of printing the escape character(\) instead, then if user mention it in a string interpreter will think of it as escape character and will not print it. In order to print the escape character user have to use escape character before '\' as shown in the example.
Python
# Print Escape character
print (" \\ is back slash ")
8. String Comparison is Case-Sensitive
Python string comparisons are case-sensitive. This means that "hello" and "Hello" are considered different strings. This allows for precise string matching, but it’s also important to handle case sensitivity when comparing user input or working with text data.
Python
print("hello" == "Hello")
9. Strings Can Be Multiline
You can create multiline strings in Python using triple quotes (""" or '''). Multiline strings are useful for writing longer pieces of text or docstrings for functions and classes.
Python
s = """This is
a multiline
string"""
print(s)
OutputThis is
a multiline
string
10. Strings Can Be Reversed
You can reverse a string using slicing with a step of -1. Reversing strings can be helpful in various tasks, such as palindromes or analyzing strings from right to left.
Python
s = "GeeksForGeeks"
print(s[::-1])
Fun Features in Python Strings
1. Strings Can Be Sliced
Python allows you to slice strings, which means you can extract a portion of the string by specifying a range of indices. String slicing makes it easy to extract parts of a string for further processing or analysis.
Example:
Python
s = "hello"
print(s[1:4])
2. Strings Can Be Split into Lists
The split() method splits a string into a list based on a specified delimiter (by default, it splits by whitespace). Splitting strings is useful for tasks like parsing sentences or processing user input into individual components.
Example:
Python
s = "Geeks For Geeks"
words = s.split()
print(words)
Output['Geeks', 'For', 'Geeks']
Python provides multiple ways to format strings, such as the old % formatting method, str.format() method, and f-strings (available in Python 3.6+). String formatting makes it easier to construct dynamic strings, especially when dealing with variables.
Example:
Python
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
OutputMy name is Alice and I am 25 years old.
String built-in Methods
Python strings come with a variety of built-in methods that allow you to manipulate and interact with text in powerful ways. Here’s a list of some commonly used string methods:
1. lower()
Converts all characters in the string to lowercase.
Example:
Python
s = "GEEKS FOR GEEKS"
print(s.lower())
2. replace(old, new)
Replaces occurrences of a substring (old) with another substring (new).
Example:
Python
s = "Hello World"
print(s.replace("World", "Python"))
3. find(sub)
Returns the index of the first occurrence of the specified substring (sub). Returns -1 if the substring is not found.
Python
s = "Hello World"
print(s.find("World"))
print(s.find("Python"))
4. count(sub)
Returns the number of occurrences of the specified substring (sub) in the string.
Python
s = "Geeks For Geeks"
print(s.count("Geeks"))
5. isdigit()
Returns True if all characters in the string are digits.
Python
s = "12345"
print(s.isdigit())
s = "Hello123"
print(s.isdigit())
Explore in detail about - Python String Methods
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Types of Network Topology
Network topology refers to the arrangement of different elements like nodes, links, or devices in a computer network. Common types of network topology include bus, star, ring, mesh, and tree topologies, each with its advantages and disadvantages. In this article, we will discuss different types of n
12 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read