Working with Strings in Python 3 - GeeksforGeeks (2024)

Last Updated : 31 Jul, 2023

Summarize

Comments

Improve

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 GeekCreating String with double quotes : yes, I am GeekCreating 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"')

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

Working with Strings in Python 3 - GeeksforGeeks (1)

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 : GThe 2nd element is : EThe 3rd element is : EThe 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 : KThe 3rd element is : EThe 2nd element is : EThe 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 GeeksAfter updating : GeeksforgeeksUpdated 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

GeeGeekfoeekfor

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

GeekforgeekGeekforge

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

GeekforgeeksefrekskeegrofkeeG

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 geeksYes, I am GeekThere are total 36 booksGeeksforgeeks is a computer science portal for Geeks

Note:For more information, referf-strings in Python 3 – Formatted string literals

Related Resources:

  • To learn more about Python 3, visit: Python 3 Tutorial


kumar_satyam

Working with Strings in Python 3 - GeeksforGeeks (3)

Improve

Previous Article

Python String

Next Article

Why are Python Strings Immutable?

Please Login to comment...

Working with Strings in Python 3 - GeeksforGeeks (2024)
Top Articles
Council Post: What Do Business Lenders Look For In Your Application?
API Endpoints Protection Using JWT
Fighter Torso Ornament Kit
Craigslist Myrtle Beach Motorcycles For Sale By Owner
Shoe Game Lit Svg
Ffxiv Palm Chippings
Dee Dee Blanchard Crime Scene Photos
Craigslist Dog Sitter
Scentsy Dashboard Log In
Strange World Showtimes Near Amc Braintree 10
Bill Devane Obituary
Chicken Coop Havelock Nc
The fabulous trio of the Miller sisters
Learn2Serve Tabc Answers
Dc Gas Login
Samantha Lyne Wikipedia
Pizza Hut In Dinuba
Costco Gas Foster City
Band Of Loyalty 5E
Is The Yankees Game Postponed Tonight
Halo Worth Animal Jam
Gayla Glenn Harris County Texas Update
Wbiw Weather Watchers
Dragonvale Valor Dragon
Sister Souljah Net Worth
Hannaford Weekly Flyer Manchester Nh
4Oxfun
Black Lion Backpack And Glider Voucher
Taylored Services Hardeeville Sc
Primerica Shareholder Account
Home Auctions - Real Estate Auctions
"Pure Onyx" by xxoom from Patreon | Kemono
Hermann Memorial Urgent Care Near Me
The Complete Guide To The Infamous "imskirby Incident"
Merge Dragons Totem Grid
Mta Bus Forums
Nobodyhome.tv Reddit
Husker Football
Lovein Funeral Obits
Dispensaries Open On Christmas 2022
Lyndie Irons And Pat Tenore
FedEx Authorized ShipCenter - Edouard Pack And Ship at Cape Coral, FL - 2301 Del Prado Blvd Ste 690 33990
Sacramentocraiglist
Market Place Tulsa Ok
9294027542
10 Bedroom Airbnb Kissimmee Fl
Strange World Showtimes Near Atlas Cinemas Great Lakes Stadium 16
Wieting Funeral Home '' Obituaries
Ark Silica Pearls Gfi
Factorio Green Circuit Setup
Leslie's Pool Supply Redding California
Latest Posts
Article information

Author: Mr. See Jast

Last Updated:

Views: 6326

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.