Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Why are Python Strings Immutable?
Next article icon

A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.

Python
s="GfG"print(s[1])# access 2nd chars1=s+s[0]# updateprint(s1)# print

Output
fGfGG

In this example,s holds the value "GfG" and is defined as a string.

Creating a String

Strings can be created using eithersingle (')or double (")quotes.

Python
s1='GfG's2="GfG"print(s1)print(s2)

Output
GfGGfG

Multi-line Strings

If we need a string to span multiple lines then we can usetriple quotes (''' or """).

Python
s="""I am LearningPython String on GeeksforGeeks"""print(s)s='''I'm aGeek'''print(s)

Output
I am LearningPython String on GeeksforGeeksI'm a Geek

Accessing characters in Python String

Strings in Python are sequences of characters, so we can access individual characters usingindexing. Strings are indexed starting from0and-1 from end. This allows us to retrieve specific characters from the string.

Python String syntax indexing
Python
s="GeeksforGeeks"# Accesses first character: 'G'print(s[0])# Accesses 5th character: 's'print(s[4])

Output
Gs

Note:Accessing an index out of range will cause anIndexError. Only integers are allowed as indices and using a float or other types will result in aTypeError.

Access string withNegative Indexing

Python allows negative address references to access characters from back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on. 

Python
s="GeeksforGeeks"# Accesses 3rd character: 'k'print(s[-10])# Accesses 5th character from end: 'G'print(s[-5])

Output
kG

String Slicing

Slicingis a way to extract portion of a string by specifying thestartandendindexes. The syntax for slicing isstring[start:end], wherestartstarting index andendis stopping index (excluded).

Python
s="GeeksforGeeks"# Retrieves characters from index 1 to 3: 'eek'print(s[1:4])# Retrieves characters from beginning to index 2: 'Gee'print(s[:3])# Retrieves characters from index 3 to the end: 'ksforGeeks'print(s[3:])# Reverse a stringprint(s[::-1])

Output
eekGeeksforGeeksskeeGrofskeeG

String Immutability

Strings in Python are immutable. This means that they cannot be changed after they are created. If we need to manipulate strings then we can use methods likeconcatenation, slicing,orformatting to create new strings based on the original.

Python
s="geeksforGeeks"# Trying to change the first character raises an error# s[0] = 'I'  # Uncommenting this line will cause a TypeError# Instead, create a new strings="G"+s[1:]print(s)

Output
GeeksforGeeks

Deleting a String

In Python, it is not possible to delete individual characters from a string since strings are immutable. However, we can delete an entire string variable using thedelkeyword.

Python
s="GfG"# Deletes entire stringdels

Note:After deleting the string usingdeland if we try to accesss then it will result in aNameError because the variable no longer exists.

Updating a String

To update a part of a string we need to create a new string since strings are immutable.

Python
s="hello geeks"# Updating by creating a new strings1="H"+s[1:]# replacnig "geeks" with "GeeksforGeeks"s2=s.replace("geeks","GeeksforGeeks")print(s1)print(s2)

Output
Hello geekshello GeeksforGeeks

Explanation:

  • For s1,The original strings is sliced from index 1 to end of string and then concatenate "H" to create a new strings1.
  • For s2, we can created a new string s2 and usedreplace() method to replace 'geeks' with 'GeeksforGeeks'.

Common String Methods

Python provides a various built-in methods to manipulate strings. Below are some of the most useful methods.

len(): Thelen() function returns the total number of characters in a string.

Python
s="GeeksforGeeks"print(len(s))# output: 13

Output
13

upper() and lower():upper() method converts all characters to uppercase.lower()method converts all characters to lowercase.

Python
s="Hello World"print(s.upper())# output: HELLO WORLDprint(s.lower())# output: hello world

Output
HELLO WORLDhello world

strip() and replace():strip() removes leading and trailing whitespace from the string andreplace(old, new)replaces all occurrences of a specified substring with another.

Python
s="   Gfg   "# Removes spaces from both endsprint(s.strip())s="Python is fun"# Replaces 'fun' with 'awesome'print(s.replace("fun","awesome"))

Output
GfgPython is awesome

To learn more about string methods, please refer toPython String Methods.

Concatenating and Repeating Strings

We can concatenate strings using+ operatorand repeat them using* operator.

Strings can be combined by using+ operator.

Python
s1="Hello"s2="World"s3=s1+" "+s2print(s3)

Output
Hello World

We can repeat a string multiple times using* operator.

Python
s="Hello "print(s*3)

Output
Hello Hello Hello

Formatting Strings

Python provides several ways to include variables inside strings.

Using f-strings

The simplest and most preferred way to format strings is by usingf-strings.

Python
name="Alice"age=22print(f"Name:{name}, Age:{age}")

Output
Name: Alice, Age: 22

Using format()

Another way to format strings is by usingformat()method.

Python
s="My name is{} and I am{} years old.".format("Alice",22)print(s)

Output
My name is Alice and I am 22 years old.

Usingin for String Membership Testing

Theinkeywordchecks if a particular substring is present in a string.

Python
s="GeeksforGeeks"print("Geeks"ins)print("GfG"ins)

Output
TrueFalse

Quiz:

Related Articles:

Recommended Problems:


Python String
Visit Courseexplore course icon
Video Thumbnail

Python String

Video Thumbnail

String Operations in Python [Part -1]

Video Thumbnail

String Operations in Python [Part -2]

Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp