Working with Strings in Python 3
Last Updated :
31 Jul, 2023
In Python, sequences of characters are referred to as Strings. It used in Python to record text information, such as names. Python strings are “immutable” which means they cannot be changed after they are created.
Creating a String
Strings can be created using single quotes, double quotes, or even triple quotes. Python treats single quotes the same as double-quotes.
Python3
String = 'Hello Geek'
print("Creating string with single quotes :", String)
String = "yes, I am Geek"
print("Creating String with double quotes :", String)
String =
print("Creating String with triple quotes :", String)
|
Output
Creating string with single quotes : Hello Geek
Creating String with double quotes : yes, I am Geek
Creating String with triple quotes : yes, I am Geek
Note: Be careful with quotes!
Python3
String = 'Yes' I am geek'
print(String)
|
Output
File "<ipython-input-10-794636cfedda>", line 3
String = 'Yes' I am geek'
^
SyntaxError: invalid syntax
The reason for the error above is the single quote in Yes’ I stopped the string. If you want to print ‘WithQuotes’ in python, this can’t be done with only single (or double) quotes alone, it requires simultaneous use of both. The best way to avoid this error use double-quotes.
Example:
Python3
print("'WithQuotes'")
print("Hello 'Python'")
print('"WithQuotes"')
print('Hello "Python"')
|
Output
'WithQuotes'
Hello 'Python'
"WithQuotes"
Hello "Python"
Note: For more information, refer Single and Double Quotes | Python
String Indexing
Strings are a sequence of characters, which means Python can use indexes to call parts of the sequence. There are two ways of indexing.
- Positive Indexing
- Negative Indexing

Positive indexing
Python3
String = "GEEK"
print("The 1st element is : ", String[0])
print("The 2nd element is : ", String[1])
print("The 3rd element is : ", String[2])
print("The 4th element is : ", String[3])
|
Output
The 1st element is : G
The 2nd element is : E
The 3rd element is : E
The 4th element is : K
Negative indexing
Python3
String = "GEEK"
print("The 4th element is : ", String[-1])
print("The 3rd element is : ", String[-2])
print("The 2nd element is : ", String[-3])
print("The 1th element is : ", String[-4])
|
Output
The 4th element is : K
The 3rd element is : E
The 2nd element is : E
The 1th element is : G
Updating Strings
In Python, Updation or deletion of characters from a string is not allowed. This will cause an error because item assignment or item deletion from a String is not supported. Python can allow you to reassign a new string to an existing one string.
Python3
String = "Geeks"
String[0] = "Hi!, Geeks"
|
Output
Traceback (most recent call last): File “/home/b298782a4e04df4950426bf4bd5bee99.py”, line 5, in <module> String[0] = “Hi!, Geeks” TypeError: ‘str’ object does not support item assignment
Updating the entire String
Python3
String = "Hello Geeks"
print("Before updating : ", String)
String = "Geeksforgeeks"
print("After updating : ", String)
String = 'Hello World!'
print("Updated String :- ", String[:6] + 'Python')
|
Output
Before updating : Hello Geeks
After updating : Geeksforgeeks
Updated String :- Hello Python
String Slicing
Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end.
Python slicing can be done in two ways.
- slice() Constructor
- Extending Indexing
Python3
String = "Geekforgeeks"
s1 = slice(3)
print(String[s1])
print(String[:6])
print(String[1:7])
|
Slicing with negative Index.
Python3
String = "Geekforgeeks"
s1 = slice(-1)
print(String[s1])
print(String[0:-3])
|
Output
Geekforgeek
Geekforge
We can use [ : : ] for specifying the frequency to print elements. It specifies the step after which every element will be printed starting from the given index. If nothing is given then it starts from the 0th index.
Python3
String = "Geekforgeeks"
print(String[::1])
print(String[2::2])
print(String[::-1])
|
Output
Geekforgeeks
efrek
skeegrofkeeG
Note: For more information, refer String Slicing in Python
String Formatting
str.format() and f-strings methods are used to add formatted objects to printed string statements. The string format() method formats the given string. It allows for multiple substitutions and value formatting.
Python3
String = 'Geeksforgeeks'
print("{}, A computer science portal for geeks."
.format(String))
String = 'Geeks'
print("Hello {}, How are you ?".format(String))
val = 2
print("I want {} Burgers! ".format(val))
|
Output
Geeksforgeeks, A computer science portal for geeks.
Hello Geeks, How are you ?
I want 2 Burgers!
Note: For more information, refer Python | format() function
Formatted f-string literals are prefixed with ‘f’ and curly braces { } containing expressions that will be replaced with their values.
Python3
String = 'GeekForGeeks'
print(f"{String}: A Computer Science portal for geeks")
String = 'Geek'
print(f"Yes, I am {String}")
bags = 3
book_in_bag = 12
print(f'There are total {bags * book_in_bag} books')
Dic = {'Portal': 'Geeksforgeeks', 'for': 'Geeks'}
print(f"{Dic['Portal']} is a computer science portal for {Dic['for']}")
|
Output
GeekForGeeks: A Computer Science portal for geeks
Yes, I am Geek
There are total 36 books
Geeksforgeeks is a computer science portal for Geeks
Note: For more information, refer f-strings in Python 3 – Formatted string literals
Related Resources:
Similar Reads
Working with Strings in Python 3
In Python, sequences of characters are referred to as Strings. It used in Python to record text information, such as names. Python strings are "immutable" which means they cannot be changed after they are created. Creating a StringStrings can be created using single quotes, double quotes, or even tr
6 min read
Working with Unicode in Python
Unicode serves as the global standard for character encoding, ensuring uniform text representation across diverse computing environments. Python, a widely used programming language, adopts the Unicode Standard for its strings, facilitating internationalization in software development. This tutorial
3 min read
f-strings in Python
Python offers a powerful feature called f-strings (formatted string literals) to simplify string formatting and interpolation. f-strings is introduced in Python 3.6 it provides a concise and intuitive way to embed expressions and variables directly into strings. The idea behind f-strings is to make
5 min read
Python - String startswith()
startswith() method in Python is a built-in string method that checks whether a given string starts with a specific prefix. It helps in efficiently verifying whether a string begins with a certain substring, which can be useful in various scenarios like filtering or validating input. In this article
3 min read
How to Substring a String in Python
A String is a collection of characters arranged in a particular order. A portion of a string is known as a substring. For instance, suppose we have the string "GeeksForGeeks". In that case, some of its substrings are "Geeks", "For", "eeks", and so on. This article will discuss how to substring a str
4 min read
string.whitespace in Python
In Python, string.whitespace is a string containing all the characters that are considered whitespace. Whitespace characters include spaces, tabs, newlines and other characters that create space in text. string.whitespace constant is part of the string module, which provides a collection of string o
3 min read
C strings conversion to Python
For C strings represented as a pair char *, int, it is to decide whether or not - the string presented as a raw byte string or as a Unicode string. Byte objects can be built using Py_BuildValue() as // Pointer to C string data char *s; // Length of data int len; // Make a bytes object PyObject *obj
2 min read
Fill a Python String with Spaces
This article will show you to fill out a python string with spaces to the left, right, and around a string in Python. Let's suppose we have a string GeeksforGeeks, and we want to fill N number of spaces on left, right, and around the string. Note that in the case of space around the string if N is o
4 min read
Convert binary to string using Python
The process of converting a binary string to a text string involves interpreting the binary data as human-readable characters. We can do this using methods like the int() function, list comprehension and binascii module. Using int() and chr()This is the simplest and most efficient method. We first c
3 min read
Convert string to title case in Python
In this article, we will see how to convert the string to a title case in Python. The str.title() method capitalizes the first letter of every word. [GFGTABS] Python s = "geeks for geeks" result = s.title() print(result) [/GFGTABS]OutputGeeks For Geeks Explanation: The s.title() method con
2 min read