Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views8 pages

List+and+String Manipulation

Uploaded by

lancer6yt
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)
6 views8 pages

List+and+String Manipulation

Uploaded by

lancer6yt
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
You are on page 1/ 8

String Manipulation in Python

Strings are immutable, ordered sequences of characters.

They are used to represent text and support a wide range of operations for processing and
transforming text data.

1. Creating Strings

Syntax:

• Single quotes: 'hello'


• Double quotes: "hello" (equivalent to single quotes)

Escape Characters:

• \n: Newline
• \t: Tab
• \\: Backslash
• \' or \": Include quotes in string
• Example: print("Line\nbreak")
• Output: Line

Break

2. Accessing and Slicing Strings

Indexing: Access individual characters using zero-based indices.

• Example: s = "Python"; s[0] → 'P'


• Negative indexing: s[-1] → 'n' (last character)

Slicing: Extract substrings with [start:end:step].

• start: Inclusive start index (default 0)


• end: Exclusive end index (default length of string)
• step: Step size (default 1, negative for reverse)
• Examples:
• s[1:4] → 'yth' (characters from index 1 to 3)
• s[:3] → 'Pyt' (start to index 2)
• s[::2] → 'Pto' (every second character)
• s[::-1] → 'nohtyP' (reverse string)

1. String Immutability
• Strings cannot be modified in place. Operations like replace or concatenation create new
strings.
• Example:

1. Common String Methods

Python provides a rich set of built-in methods for string manipulation:

Method Description Example

str.lower() Converts string to lowercase

Converts string to lowercase


str.upper()

Capitalizes first letter of each


str.title() word

Removes leading/trailing
str.strip() whitespace

Removes leading whitespace


str.lstrip()
Removes trailing whitespace
str.rstrip()

Replaces all occurrences of


str.replace(Old,
old with new
New)

Splits string into a list based on


str.split(sep) sep (default: whitespace)

Joins elements of iterable into


str.join(iterable) a string with s as separator

Returns lowest index of sub or


str.find(sub) -1 if not found

Returns highest index of sub


str.rfind(sub) or -1 if not found

Like find, but raises ValueError


str.index(sub) if not found

Counts occurrences of sub


str.count(sub)

Returns True if string starts


str.startswith(prefix) with prefix

Returns True if string ends with


str.endswith(prefix) suffix

Returns True if all characters


str.isalpha() are alphabetic

Returns True if all characters


str.isdigit() are digits

Returns True if all characters


str.isalnum() are alphanumeric

Returns True if all characters


str.isspace() are whitespace
Capitalizes first character, rest
str.capitalize() lowercase

5. String Formatting

• Concatenation: Combine strings using +.


• Example: "Hello, " + "World!" → 'Hello, World!'
• f-strings (Python 3.6+): Embed expressions inside string literals.
• Example: name = "Alice"; f"Hello, {name}" → 'Hello, Alice'
• str.format(): Format strings with placeholders.
• Example: "Hello, {}".format("Alice") → 'Hello, Alice'
• % Operator: Older style formatting.
• Example: "Hello, %s" % "Alice" → 'Hello, Alice'

6. String Performance Tips

• Use join instead of + for concatenating many strings (more efficient).


• Example: ''.join(['a', 'b', 'c']) is faster than 'a' + 'b' + 'c'.
• For large strings, consider str.join() for efficiency.

List Manipulation in Python


Lists are mutable, ordered collections of elements that can hold items of any type (integers, strings,
objects, etc.).

They are versatile and widely used for data manipulation.

1. Creating Lists

• Syntax:
• lst = [1, 2, 3]
• Empty list: lst = []
• Mixed types: lst = [1, "hello", True]
• List comprehension: lst = [x for x in range(5)] → [0, 1, 2, 3, 4]
• From other iterables: lst = list("hello") → ['h', 'e', 'l', 'l', 'o']

2. Accessing and Slicing Lists

• Indexing: Access elements using zero based indices.


• Example: lst = [10, 20, 30]; lst[1] → 20
• Negative indexing: lst[-1] → 30
• Slicing: Extract sublists with [start:end:step].
• Examples:
• lst[1:3] → [20, 30]
• lst[:2] → [10, 20]
• lst[::2] → [10, 30]
• lst[::-1] → [30, 20, 10] (reverse)

3. Modifying Lists

• Change elements:
• lst[0] = 100 → [100, 20, 30]
• Append: Add single element to end.
• lst.append(40) → [100, 20, 30, 40]
• Insert: Add element at specific index.
• lst.insert(1, 15) → [100, 15, 20, 30, 40]
• Remove:
• lst.remove(20): Removes first occurrence of 20 → [100, 15, 30, 40]
• lst.pop(): Removes and returns last element → 40
• lst.pop(index): Removes and returns element at index
• del lst[1]: Deletes element at index 1 → [100, 30, 40]
• lst.clear(): Removes all elements → []
• Extend: Add multiple elements from an iterable.
• lst.extend([50, 60]) → [100, 30, 40, 50, 60]

4. Common List Methods

Method Description Example


lst.append(x) Adds x to end of list

lst.extend(iter) Adds elements from iter to end

lst.insert(i, x Inserts x at index i

lst.remove(x) Removes first occurrence of x


(raises ValueError if not found)

lst.pop(i) Removes and returns element at


index i (default: last)

lst.clear() Removes all elements

lst.index(x) Returns first index of x (raises


ValueError if not found)

lst.count(x) Counts occurrences of x

lst.sort() Sorts list in place (accepts key


and reverse arguments)

lst.reverse()
Reverses list in place

lst.copy()
Returns shallow copy of list

5. List Comprehension

• Concise way to create lists using a single line.


• Syntax: [expression for item in iterable if condition]
• Examples:
• [x*2 for x in [1, 2, 3]] → [2, 4, 6]
• [x for x in [1, 2, 3, 4] if x % 2 == 0] → [2, 4]
• Nested: [[0 for _ in range(3)] for _ in range(2)] → [[0, 0, 0], [0, 0, 0]]
6. Copying Lists

• Shallow Copy: Copies top-level elements, but nested objects are referenced.
• new_lst = lst.copy() or new_lst = lst[:]
• Example:

Key Differences Between Strings and Lists

Feature String List

Immutable (cannot change


Mutability Mutable (can change elements)
characters)

Data Types Only characters Any type (integers, strings, objects)

Text-specific (e.g., upper,


Methods General-purpose (e.g., append, sort)
split)

Syntax 'hello' or "hello" [1, 2, 3]

Concatenation +, join +, extend

Additional Resources

https://docs.python.org/3/tutorial/datastructures.html

https://docs.python.org/3/library/stdtypes.html#string-methods
https://www.w3schools.com/python/python_lists_methods.asp

https://www.w3schools.com/python/python_ref_string.asp

You might also like