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

Mastering String Methods in Python

This document presents an overview of essential Python string methods for text manipulation, including immutability, concatenation, indexing, and various string operations. Key methods such as upper(), find(), strip(), split(), and replace() are explained with examples. It emphasizes the importance of understanding string immutability and encourages consulting official documentation for best practices.

Uploaded by

ashishkv9669
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)
5 views8 pages

Mastering String Methods in Python

This document presents an overview of essential Python string methods for text manipulation, including immutability, concatenation, indexing, and various string operations. Key methods such as upper(), find(), strip(), split(), and replace() are explained with examples. It emphasizes the importance of understanding string immutability and encourages consulting official documentation for best practices.

Uploaded by

ashishkv9669
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

Ma teri g Stri g Met od i

Pyt o
Python strings are fundamental for text manipulation, data parsing,
and user input. This presentation explores essential string methods,
crucial for any Python developer. We'll delve into their functionalities
and practical applications.

- By Vaishnavi Prakash Srivastava


Stri g Ba ic : I utability a d Operatio
Immutability: Python strings are immutable. Once created,
their content cannot be changed. Any operation that seems
to modify a string, in fact, returns a new string.

Concatenation: Combine strings using the + operator. For


instance, "Py" + "thon" yields "Python".

Indexing: Access individual characters using square


brackets. s[0] gets the first character, s[-1] gets the last.

Slicing: Extract substrings using slicing. s[1:4] extracts


characters from index 1 up to (but not including) 4. For
example, from "Python", it gives "yth".

Length: Determine string length with len(). len("Python")


returns 6.
Ca e Co ver io a d Capitali atio Met od

upper() lower() capitalize()


Converts all characters to uppercase. Converts all characters to lowercase. First character uppercase, rest
E.g., "python".upper() gives "PYTHON". E.g., "PYTHON".lower() gives "python". lowercase. E.g., "python".capitalize()
gives "Python".

title() swapcase()
First character of each word Swaps the case of all characters. E.g.,
uppercase. E.g., "hello world".title() "PyThOn".swapcase() gives "pYtHoN".
gives "Hello World".
Searc i g a d Validatio Met od
find(substring): Returns the lowest index of the
substring, or -1 if not found. E.g., "apple".find("pl")
returns 2.

count(substring): Returns the number of non-


overlapping occurrences. E.g., "banana".count("na")
returns 2.

startswith(prefix): Returns True if the string starts with


the prefix. E.g., "file.txt".startswith("file") returns True.

endswith(suffix): Returns True if the string ends with


the suffix. E.g., "data.csv".endswith(".csv") returns True.

Validation Methods: isalnum(), isalpha(), isdigit() check


if all characters are alphanumeric, alphabetic, or
digits, respectively. E.g., "123".isdigit() returns True.
W ite pace a d Alig e t
Met od
strip()

Removes leading and trailing whitespace. E.g., " Hello ".strip()


gives "Hello".

lstrip() rstrip()

lstrip() removes leading whitespace; rstrip() removes trailing


whitespace.

d
zfill(wi th)

Pads the string with leading zeros to the specified width. E.g.,
"42".zfill(5) gives "00042".

Alig e t Met od
ljust(width, char), rjust(width, char), and center(width, char) left,
right, or center align the string with a specified padding
character. E.g., "Hi".center(10, '*') gives "****Hi****".
Splitti g a d Joi i g Met od
split(delimiter): Splits the string into a list of substrings
based on a delimiter. E.g.,
"apple,banana,orange".split(",") results in ['apple',
'banana', 'orange'].

partition(separator): Splits the string into a 3-tuple:


(before separator, separator, after separator). E.g.,
"name=John".partition("=") gives ('name', '=', 'John').

join(iterable): Concatenates elements of an iterable


(like a list) using the string itself as the separator. E.g.,
", ".join(["A", "B", "C"]) results in "A, B, C".
Replace e t a d
Tra latio Met od
replace(old, new, count) maketrans(x, y, z)
Replaces all occurrences of Creates a translation table
old with new. The optional for translate(). x contains
count limits replacements. characters to replace, y their
E.g., "hello world".replace("o", replacements, and z
"X") gives "hellX wXrld". characters to delete.

translate(table)
Maps characters using the translation table created by
maketrans(). E.g., s.translate(str.maketrans("aeiou", "12345")) for
vowel replacement.
Co clu io a d Be t Practice

1 Co ult Doc

2 I utability

3 F- tri g .for at()

4 Powerful Efficie t

Python's string methods are incredibly powerful and efficient tools for text manipulation. Always remember that strings
are immutable, so methods return new strings. For complex formatting, leverage the versatility of f-strings or .format().
Finally, always consult the official Python documentation for specific method behaviours and edge cases to ensure
robust and error-free code.

You might also like