0% found this document useful (0 votes)
15 views5 pages

Python Strings: Key Concepts & Methods

This document provides an overview of Python strings, defining them as sequences of characters that can be enclosed in single, double, or triple quotes. It covers key characteristics such as immutability, indexing, slicing, concatenation, and built-in functions, along with various string methods for case manipulation, searching, counting, replacing, and splitting. Examples are provided to illustrate the usage of these concepts in Python.

Uploaded by

Geet Vashishtha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views5 pages

Python Strings: Key Concepts & Methods

This document provides an overview of Python strings, defining them as sequences of characters that can be enclosed in single, double, or triple quotes. It covers key characteristics such as immutability, indexing, slicing, concatenation, and built-in functions, along with various string methods for case manipulation, searching, counting, replacing, and splitting. Examples are provided to illustrate the usage of these concepts in Python.

Uploaded by

Geet Vashishtha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Strings – Class 11 Notes

1.

What is a String?
A string is a sequence of characters enclosed in:

●​ Single quotes ' '​

●​ Double quotes " "​

●​ Triple quotes ''' ''' or """ """ (for multiline strings)


●​ s1 = 'Hello'
●​ s2 = "World"
●​ s3 = '''This is
●​ a multi-line string''
●​ ​
2.

String Characteristics
●​ Strings are immutable → once created, they cannot be changed.​

●​ Strings are ordered → index-based access is possible.​

●​ Strings support slicing and many built-in methods.​

3.

Accessing Characters (Indexing

H e l l o
0 1 2 3 4
Negative indexing:

H e l l o
-5 -4 -3 -2 -1

s = "Hello"

print(s[0]) # H
print(s[-1]) # o

4. String Slicing

string[start:end:step]

●​ start → index to begin​

●​ end → index before which to stop​

●​ step → interval​

Examples:

s = "HelloWorld"
print(s[0:5]) # Hello
print(s[2:8]) # lloWor
print(s[:5]) # Hello
print(s[5:]) # World
print(s[::-1]) # reverse string

5. String Concatenation & Repetition

a = "Hello"
b = "World"

print(a + " " + b) # Hello World


print(a * 3) # HelloHelloHello
6. Useful Built-in Functions

Function Description Example

len() returns length len("hello") → 5

max() largest character max("hello") → ‘o’

min() smallest character min("Cat") → ‘C’

sorted() returns sorted characters list sorted("bca") → [‘a’,‘b’,‘c’]

7. String Methods
Changing Case

Method Result

upper() uppercase

lower() lowercase

title() first letter caps each word


capitalize() First letter uppercase

swapcase() Reverse letter case

s = "hello python"
print([Link]()) # HELLO PYTHON
print([Link]()) # Hello Python

Searching & Counting

Method Description

find(sub) returns index of substring OR -1

index(sub) same, but error if not found

count(sub) number of occurrences

s = "banana"
print([Link]("na")) # 2
print([Link]("a")) # 3

Replace & Strip

Method Description

replace(old, new) replaces substring


strip() removes spaces at both ends

lstrip() removes left spaces

rstrip() removes right spaces

s = " hello "


print([Link]()) # hello
print("banana".replace("na", "NA")) # baNANA

Splitting & Joining


s = "apple,banana,mango"
x = [Link](",") # ['apple','banana','mango']
print("-".join(x)) # apple-banana-mango

Common questions

Powered by AI

The immutability of strings in Python results in each modification, such as through concatenation or slicing, causing a new string object to be created. This behavior can lead to increased memory usage and can impact performance in applications with numerous string manipulations. Efficient management involves minimizing unnecessary modifications or using alternative data structures for frequent updates, thus avoiding excessive memory consumption .

Python's string methods such as upper(), lower(), capitalize(), and title() manipulate the case of strings, which can standardize text format for uniformity and readability. Methods like replace() and strip() modify the content or cleanliness of strings by replacing parts or trimming whitespace, crucial for data sanitization. For instance, using capitalize() on 'hello world' results in 'Hello world', improving its presentability .

The split() method divides a string into a list of substrings based on a specified separator, effectively converting a single string into organized data segments. For instance, calling split(',') on 'apple,banana,mango' produces ['apple', 'banana', 'mango'], facilitating operations like iteration or analysis on individual elements. This method is essential in parsing CSV strings or log entries .

Concatenation (using '+') combines strings, facilitating the construction of dynamic and readable output, such as merging user input with static text. Repetition (using '*') efficiently constructs repeated patterns or padding. However, these techniques can lead to inefficient memory usage and slower execution with very large strings since each operation leads to the creation of a new string due to immutability .

Using replace() on large text blocks may lead to performance degradation due to the creation of new strings for each operation, especially when replacements are numerous. Moreover, unintended replacements could alter text meaning if not adequately controlled. Mitigation strategies include pre-validation of replacements, batching operations, and considering alternative data structures to reduce overhead .

The sorted() function reorders characters in a string lexicographically, aiding in text normalization where consistent order facilitates comparison, duplicate detection, and canonicalization. For example, sorting 'bca' results in ['a', 'b', 'c'], establishing a standard order crucial in applications like checksum generation or data deduplication .

String indexing, including negative indices, allows precise character access from both ends of a string. This dual-direction capability simplifies tasks such as reverse iteration or sub-sections extraction. Negative indices provide greater flexibility, obviating cumbersome length calculations. Proper use can enhance clarity and efficiency but requires careful boundary management to avoid IndexError exceptions .

Python strings are immutable, meaning once a string is created, it cannot be altered. This immutability ensures that strings are safe from accidental changes, making code more reliable but requiring workarounds for modifications. Strings are also ordered, allowing index-based access which facilitates precise string manipulation through indexing and slicing. These features make strings powerful for text processing but can introduce complexity when manipulation is needed .

String slicing in Python follows the format string[start:end:step], enabling access to a substring defined by start and end indices with an optional step. Using negative indices allows traversal from the string's end, offering flexibility in scenarios where the relative position from the end is relevant. For example, s[::-1] reverses a string by stepping backwards .

Methods like find() and count() are vital for searching and quantifying occurrences of sub-strings within larger data sets, aiding in pattern recognition and frequency analysis. When using find(), one must handle the potential return of -1 (not found), while count() provides total occurrences, crucial for statistical insights. Consideration is needed for case sensitivity and performance on large strings .

You might also like