0% found this document useful (0 votes)
2 views6 pages

Essential String and Tuple Methods Guide

The document provides a comprehensive overview of string and tuple methods in Python, detailing their descriptions, code examples, and expected outputs. It includes various string methods such as capitalize, count, and isalnum, as well as tuple functions like all, any, and len. Each method is listed with its purpose and a placeholder for code and output, making it a useful reference for programming in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

Essential String and Tuple Methods Guide

The document provides a comprehensive overview of string and tuple methods in Python, detailing their descriptions, code examples, and expected outputs. It includes various string methods such as capitalize, count, and isalnum, as well as tuple functions like all, any, and len. Each method is listed with its purpose and a placeholder for code and output, making it a useful reference for programming in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Name:

Roll No:
Class: SY BCA Science - E

String Methods

[Link]. Methods Description Code & Output


1. Capitalize() Capitalizes first Code:
letter of string
Output:

2. count(str, beg= 0, end=len(string)) Counts how many Code:


times str occurs in
string or in a Output:
substring of string
if starting
index beg and
ending index end
are
given.
3. endswith(suffix, beg=0, Determines if Code:
end=len(string)) string or a
substring of Output:
string (if starting
index beg and
ending
index end are
given) ends with
suffix;
returns true if so
and false
otherwise.
4. isalnum() Returns true if Code:
string has at least
1 Output:
character and all
characters are
alphanumeric and
false otherwise.

5. isalpha() Returns true if Code:


string has at least
1
character and all Output:
characters are
alphabetic
and false
otherwise.
6. isdigit() Returns true if Code:
string contains
only digits Output:
and false
otherwise.
7. islower() Returns true if Code:
string has at least
1 cased Output:
character and all
cased characters
are in
lowercase and
false otherwise.
8. isnumeric() Returns true if a Code:
unicode string
contains
only numeric Output:
characters and
false
otherwise.
9. isspace() Returns true if Code:
string contains
only Output:
whitespace
characters and
false
otherwise.
10. istitle() Returns true if Code:
string is properly
"titlecased" and Output:
false otherwise.
11. isupper() Returns true if Code:
string has at least
one Output:
cased character
and all cased
characters
are in uppercase
and false
otherwise.
12. join(seq) Merges Code:
(concatenates) the
string Output:
representations of
elements in
sequence
seq into a string,
with separator
string.
13. len(string) Returns the length Code:
of the string.
Output:
14. ljust(width[, fillchar]) Returns a space- Code:
padded string with
the Output:
original string left-
justified to a total
of
width columns.
15. lower() Converts all Code:
uppercase letters
in string to Output:
lowercase.
16. lstrip() Removes all Code:
leading
whitespace in Output:
string.
17. maketrans() Returns a Code:
translation table to
be used in Output:
translate function.
18. max(str) Returns the max Code:
alphabetical
character Output:
from the string str.
19. min(str) Returns the min Code:
alphabetical
character Output:
from the string str.
20. replace(old, new [, max]) Replaces all Code:
occurrences of old
in string Output:
with new or at
most max
occurrences if
max given.
21. rfind(str, beg=0,end=len(string)) Same as find(), Code:
but search
backwards in Output:
string.
22. rjust(width,[, fillchar]) Returns a space- Code:
padded string with
the Output:
original string
right-justified to a
total of
width columns.
23. rstrip() Removes all Code:
trailing whitespace
of string. Output:
24. split(str="", num=[Link](str)) Splits string Code:
according to
delimiter str Output:
(space if not
provided) and
returns list of
substrings; split
into at most num
substrings if given.
25. splitlines( num=[Link]('\n')) Splits string at all Code:
(or num)
NEWLINEs Output:
and returns a list
of each line with
NEWLINEs
removed.
26. swapcase() Inverts case for all Code:
letters in string.
Output:
27. title() Returns Code:
"titlecased"
version of string, Output:
that
is, all words begin
with uppercase
and the
rest are
lowercase.
28. translate(table, deletechars="") Translates string Code:
according to
translation Output:
table str(256
chars), removing
those in
the del string.
29. upper() Converts Code:
lowercase letters
in string to Output:
uppercase.
30. zfill (width) Returns original Code:
string left padded
with zeros to a Output:
total of width
characters;
intended for
numbers, zfill()
retains any
sign given (less
one zero).
31. isdecimal() Returns true if a Code:
unicode string
contains Output:
only decimal
characters and
false
otherwise.

Tuple Functions

Serial Function Description Code & Output


No.

1. all() Return True if all elements of Code:


the tuple are true (or if the
tuple is empty). Output:

2. any() Return True if any element of Code:


the tuple is true. If the tuple is
empty, return False.
Output:

3. enumerate() Return an enumerate object. Code:


It contains the index and
value of all the items of tuple
as pairs. Output:

4. len() Return the length (the number Code:


of items) in the tuple.

Output:

5. max() Return the largest item in the Code:


tuple.

Output:

6. min() Return the smallest item in Code:


the tuple.

Output:

7. sorted() Take elements in the tuple Code:


and return a new sorted list
(does not sort the tuple itself).
Output:

8. sum() Return the sum of all Code:


elements in the tuple.
Output:

9. tuple() Convert an iterable (list, Code:


string, set, dictionary) to a
tuple.
Output:

Date: Signature

Common questions

Powered by AI

The `count()` method in Python counts the occurrences of a specified substring within a given string. When `beg` and `end` indices are provided, it counts the occurrences only within the specified slice of the string. For instance, `string.count(substring, beg, end)` will return the number of times `substring` appears in the substring from `string[beg:end]` .

`zfill()` pads a numeric string with zeros to the left until reaching a specified width, preserving the sign if present. It's beneficial in situations requiring uniform string lengths, such as aligning numerical identifiers in reports or logs for consistent presentation, e.g., turning '42' into '0042' for database keys or visual ledger entries where consistent width supports easier reading and processing by systems expecting fixed-length records .

`swapcase()` can be utilized to invert the case of each letter in a string, useful in scenarios where case-independence is desired, such as toggling visibility of certain text or creating stylistic variations of text for emphasis. It is limited by its blanket application; the transformation is indiscriminate of context or semantics, which may lead to loss of original case-dependent meanings and should be employed where full case-reversal is contextually correct .

The `title()` method capitalizes the first letter of each word in a string and converts the rest of the word's letters to lowercase, effectively creating a 'title case' format. This transformation is significant in contexts requiring standardized text appearance, such as formatting headings and important stylistic textual elements where clarity and aesthetic consistency improve readability and presentation .

Both `max()` and `min()` assess the characters of a string based on their Unicode values, determining the highest and lowest respectively. While useful separately for specific tasks, their simultaneous application may seem redundant unless contrasting extremes within the same dataset is required. They're integral in comparative analyses where identifying boundaries within character sets matters, such as sorting tasks or preparing datasets needing classification into ranges .

`isalpha()` checks if all characters in a string are alphabetic letters, returning `True` if so. `isnumeric()` checks if a string contains only numeric characters, returning `True` for strings representing numbers. Understanding these distinctions is crucial when differentiating data entries, as these methods allow for targeted validation: `isalpha()` for textual inputs and `isnumeric()` for numeric inputs, ensuring proper data types before further processing .

The `translate()` method in Python uses a translation table to alter string characters, offering a powerful tool for character replacement or deletion. This method is particularly useful when conforming strings to specific encodings or filtering unwanted characters without loops. However, since it maps values based on a 256-character table, it requires correct setup, reflecting character encoding settings to avoid unintended replacements, crucial in data sanitization and localization tasks .

The `isalnum()` method checks whether a string consists solely of alphanumeric characters (letters and numbers) and contains at least one character. If these conditions are met, it returns `True`; otherwise, it returns `False`. This method is often used in data validation processes to ensure that input strings do not contain special characters or whitespace, ensuring values are suitable for certain processing contexts like identifiers or simple usernames .

The `join()` method turns a sequence into a string by injecting it with the string it's called on, acting as a glue, while `split()` divides a string into a list of substrings based on a specified delimiter. These complementary methods facilitate transitions between strings and lists. For instance, `join()` is effective for creating CSV format strings from lists, whereas `split()` is useful for parsing CSV lines into data elements, illustrating mutual reinforcement in data serialization and deserialization processes .

`rfind()` is preferred when the intention is to locate the last occurrence of a substring within a string because it searches backward from the end of the string. In contrast, `find()` searches from the beginning. They perform similarly in returning the starting index of the substring if found. Using `rfind()` is advantageous when dealing with data where recent or last occurrences are more relevant, such as finding the last directory name in a file path .

You might also like