Open In App

Working with Strings in Python 3

Last Updated : 31 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# creating string
# with single Quotes
String = 'Hello Geek'
print("Creating string with single quotes :", String)
  
# Creating String
# with double Quotes
String = "yes, I am Geek"
print("Creating String with double quotes :", String)
  
# Creating String
# with triple Quotes
String = '''yes, I am Geek'''
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




# creating string
# with single quotes
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




# this code prints the output within quotes. 
# print WithQuotes within single quotes 
print("'WithQuotes'"
print("Hello 'Python'"
    
# print WithQuotes within single quotes 
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




# creating a string
String = "GEEK"
  
# Show first element in string
print("The 1st element is : ", String[0])
  
# Show 2nd element in string
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




# creating a string
String = "GEEK"
  
# Show last element in string
print("The 4th element is : ", String[-1])
  
# Show all element in string
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




# Creating string 
String = "Geeks"
  
# assign new character
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




# Creating string
String = "Hello Geeks"
print("Before updating : ", String)
  
# updating entire string
String = "Geeksforgeeks"
print("After updating : ", String)
  
# Update with indexing
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




# Creating a String
String = "Geekforgeeks"
  
s1 = slice(3)
  
# print everything except the first element
print(String[s1])
  
# print everything UP TO the 6th index
print(String[:6])
  
# print everything between both index
print(String[1:7])


Output

Gee
Geekfo
eekfor


Slicing with negative Index.

Python3




# Creating a String
String = "Geekforgeeks"
  
s1 = slice(-1)
  
# print everything except the last element
print(String[s1])
  
# print everything between both index
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




# Creating a String
String = "Geekforgeeks"
  
# print everything with step 1
print(String[::1])
  
# print everything with step 2
print(String[2::2])
  
# print a string backwards
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




# using format option in a simple string
String = 'Geeksforgeeks'
print("{}, A computer science portal for geeks."
      .format(String))
  
String = 'Geeks'
print("Hello {}, How are you ?".format(String))
  
# formatting a string using a numeric constant
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




# Creating string
String = 'GeekForGeeks'
print(f"{String}: A Computer Science portal for geeks")
  
# Creating string
String = 'Geek'
print(f"Yes, I am {String}")
  
# Manuplating int within {}
bags = 3
book_in_bag = 12
print(f'There are total {bags * book_in_bag} books')
  
# work with dictionaries in f-strings
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:



Previous Article
Next Article

Similar Reads

Python | Remove empty strings from list of strings
In many scenarios, we encounter the issue of getting an empty string in a huge amount of data and handling that sometimes becomes a tedious task. Let's discuss certain way-outs to remove empty strings from list of strings. Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this
7 min read
Python | Tokenizing strings in list of strings
Sometimes, while working with data, we need to perform the string tokenization of the strings that we might get as an input as list of strings. This has a usecase in many application of Machine Learning. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension + split() We can achieve this particular task using lis
3 min read
Python - Find all the strings that are substrings to the given list of strings
Given two lists, the task is to write a Python program to extract all the strings which are possible substring to any of strings in another list. Example: Input : test_list1 = ["Geeksforgeeks", "best", "for", "geeks"], test_list2 = ["Geeks", "win", "or", "learn"] Output : ['Geeks', 'or'] Explanation : "Geeks" occurs in "Geeksforgeeks string as subs
5 min read
Convert Strings to Numbers and Numbers to Strings in Python
In Python, strings or numbers can be converted to a number of strings using various inbuilt functions like str(), int(), float(), etc. Let's see how to use each of them. Example 1: Converting a Python String to an int: C/C++ Code # code # gfg contains string 10 gfg = &quot;10&quot; # using the int(), string is auto converted to int print(int(gfg)+2
2 min read
Working with Datetime Objects and Timezones in Python
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module. Getting a Datetime objectMethod 1: Using now() method A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/ob
5 min read
Python | Working with .docx module
Word documents contain formatted text wrapped within three object levels. Lowest level- Run objects, Middle level- Paragraph objects and Highest level- Document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. 1. The first step is to instal
3 min read
Internal working of list in Python
Introduction to Python lists : Python lists are internally represented as arrays. The idea used is similar to implementation of vectors in C++ or ArrayList in Java. The costly operations are inserting and deleting items near the beginning (as everything has to be moved). Insert at the end also becomes costly if preallocated space becomes full.We ca
3 min read
Internal working of Python
Python is an object-oriented programming language like Java. Python is called an interpreted language. Python uses code modules that are interchangeable instead of a single long list of instructions that was standard for functional programming languages. The standard implementation of Python is called "cpython". It is the default and widely used im
5 min read
Python | Working with Pandas and XlsxWriter | Set - 1
Python Pandas is a data analysis library. It can read, filter and re-arrange small and large datasets and output them in a range of formats including Excel. Pandas writes Excel files using the XlsxWriter modules. XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple
3 min read
Python | Working with Pandas and XlsxWriter | Set – 2
Prerequisite: : Python working with pandas and xlsxwriter | set-1 Python Pandas is a data analysis library. It can read, filter and re-arrange small and large datasets and output them in a range of formats including Excel. Pandas writes Excel files using the XlsxWriter modules. XlsxWriter is a Python module for writing files in the XLSX file format
4 min read
Article Tags :
Practice Tags :