Movatterモバイル変換


[0]ホーム

URL:


Open In App

In Python, a string is a sequence of characters enclosed in quotes. It can include letters, numbers, symbols or spaces. Since Python has no separate character type, even a single character is treated as a string with length one. Strings are widely used for text handling and manipulation.

Creating a String

Strings can be created using eithersingle ('...')or double ("...")quotes. Both behave the same.

Example: Creating two equivalent strings one with single and other with double quotes.

Python
s1='GfG'# single quotes2="GfG"# double quoteprint(s1)print(s2)

Output
GfGGfG

Multi-line Strings

Use triple quotes('''...''' ) or( """...""") for strings that span multiple lines. Newlines are preserved.

Example: Define and print multi-line strings using both styles.

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 String

Strings are indexed sequences. Positive indices start at0 from theleft; negative indices start at-1from therightas represented in below image:

frame_3086
Indices of string in reverse

Example 1: Access specific characters through positive indexing.

Python
s="GeeksforGeeks"print(s[0])# first characterprint(s[4])# 5th character

Output
Gs

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

Example 2: Read characters from the end usingnegative indices.

Python
s="GeeksforGeeks"print(s[-10])# 3rd characterprint(s[-5])# 5th character from end

Output
kG

String Slicing

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

Example: In this example we are slicing through range and reversing a string.

Python
s="GeeksforGeeks"print(s[1:4])# characters from index 1 to 3print(s[:3])# from start to index 2print(s[3:])# from index 3 to endprint(s[::-1])# reverse string

Output
eekGeeksforGeeksskeeGrofskeeG

String Iteration

Strings are iterable; you can loop through characters one by one.

Example: Here, it print each character on its own line.

Python
s="Python"forcharins:print(char)

Output
Python

Explanation: for loop pulls characters in order and each iteration prints the next character.

String Immutability

Strings are immutable,which means that they cannot be changed after they are created. If we need to manipulate strings then we can use methods likeconcatenation, slicingorformatting to create new strings based on original.

Example: In this example we are changing first character by building a new string.

Python
s="geeksforGeeks"s="G"+s[1:]# create new stringprint(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.

Example: Here, we are using del keyword to delete a string.

Python
s="GfG"dels

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

Updating a String

As strings are immutable, “updates” create new strings using slicing or methods such asreplace().

Example:This code fix the first letter and replace a word.

Python
s="hello geeks"s1="H"+s[1:]# update first characters2=s.replace("geeks","GeeksforGeeks")# replace wordprint(s1)print(s2)

Output
Hello geekshello GeeksforGeeks

Explanation:

  • s1:slice from index 1 onward and prepend "H".
  • s2:replace("geeks", "GeeksforGeeks") returns a new string.

Common String Methods

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

1.len(): Thelen() function returns the total number of characters in a string (including spaces and punctuation).

Example:

Python
s="GeeksforGeeks"print(len(s))

Output
13

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

Example:

Python
s="Hello World"print(s.upper())print(s.lower())

Output
HELLO WORLDhello world

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

Example:

Python
s="   Gfg   "print(s.strip())s="Python is fun"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.

1. Strings can be combined by using+ operator.

Example: Join two words with a space.

Python
s1="Hello"s2="World"print(s1+" "+s2)

Output
Hello World

2. We can repeat a string multiple times using* operator.

Example:Repeat a greeting three times.

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

Output
Hello Hello Hello

Formatting Strings

Python provides several ways to include variables inside strings.

1. Using f-strings

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

Example:Embed variables directly using {} placeholders.

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

Output
Name: Alice, Age: 22

2. Using format()

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

Example: Use placeholders {} and pass values positionally.

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.

String Membership Testing

inkeywordchecks if a particular substring is present in a string.

Example: Here, we are testing for the presence of substrings.

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

Output
TrueFalse

Related Links:

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
Improve

Explore

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