0% found this document useful (0 votes)
7 views11 pages

String Operations in Python

The document provides an overview of string operations in Python, highlighting their immutability and various methods for manipulation, including concatenation, slicing, and case conversion. It also covers searching, formatting, and type checking methods, along with operator precedence and categories. Additionally, it explains the use of operators with strings and their precedence in expressions.

Uploaded by

ammuardra146
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)
7 views11 pages

String Operations in Python

The document provides an overview of string operations in Python, highlighting their immutability and various methods for manipulation, including concatenation, slicing, and case conversion. It also covers searching, formatting, and type checking methods, along with operator precedence and categories. Additionally, it explains the use of operators with strings and their precedence in expressions.

Uploaded by

ammuardra146
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/ 11

String Operations

In Python, strings are immutable, which means they cannot be changed after they are created. Every
string operation that appears to "modify" a string actually creates and returns a new string.

Let's define a sample string to use in our examples:


s = " Hello, Python World! "

1. Basic Operations & Information

These are fundamental operations for concatenation, repetition, and getting basic information.

Operation /
Description Example (using s) Result
Function

Combines two or more strings into


+ (Concatenate) 'Hi' + ' ' + 'There' 'Hi There'
one.

Repeats a string a specified number


* (Repeat) 'Go! ' * 3 'Go! Go! Go! '
of times.

Returns the number of characters in


len(s) len(s) 24
the string.

Checks if a substring exists within the 'Python' in s<br/>'Java' True<br/>Tru


in / not in
string. not in s e

2. Indexing & Slicing

Used to access individual characters or parts of a string.

Example
Operation Description Result
(using s)

Accesses the character at index i. <br/>(0 is s[2] <br/> s[-


s[i] 'H' <br/> 'd'
the first, -1 is the last). 3]

Slices the string from start index up to (but


s[start:stop] s[2:7] 'Hello'
not including) stop index.

s[:stop] Slices from the beginning up to stop. s[:7] ' Hello'

s[start:] Slices from start to the end. s[9:] 'Python World! '

'Hlo yhn' <br/> '


s[start:stop:step Slices from start to stop, taking every step- s[2:15:2]
!dlroW nohtyP ,olleH
] th character. A step of -1 reverses the string. <br/> s[::-1]
'
3. Case Conversion Methods

These methods return a new string with the case of the letters modified.

Example (using
Method Description Result
s.strip())

'hello,
s.lower() Converts all uppercase characters to lowercase. 'Hello, Python'.lower()
python'

'HELLO,
s.upper() Converts all lowercase characters to uppercase. 'Hello, Python'.upper()
PYTHON'

Converts the first character to uppercase and 'hello, 'Hello,


s.capitalize()
all others to lowercase. python'.capitalize() python'

Converts the first character of each word to 'Hello,


s.title() 'hello, python'.title()
uppercase. Python'

s.swapcase( Swaps the case of all letters (lowercase 'Hello, 'hELLO,


) becomes upper, and vice versa). Python'.swapcase() pYTHON'

4. Searching & Finding Methods

These methods help locate substrings or count their occurrences.

Method Description Example (using s) Result

Returns the number of non-overlapping


s.count(sub) s.count('o') 3
occurrences of a substring sub.

Returns the lowest index where sub is s.find('Python')<br/>s.find('Java' 9<br/>-


s.find(sub)
found. Returns -1 if not found. ) 1

Like find(), but returns the highest index


s.rfind(sub) s.rfind('o') 16
(searches from the right).

Same as find(), but raises a ValueError if


s.index(sub) s.index('World') 16
sub is not found.

s.rindex(sub Same as rfind(), but raises a ValueError if


s.rindex('l') 18
) sub is not found.

5. Stripping, Splitting & Joining

Essential for cleaning strings and converting between strings and lists.

Method Description Example Result

s.strip() Removes leading and trailing s.strip() 'Hello, Python


whitespace. World!'

Removes leading (left-side) 'Hello, Python


s.lstrip() s.lstrip()
whitespace only. World! '

Removes trailing (right-side) ' Hello, Python


s.rstrip() s.rstrip()
whitespace only. World!'

Removes leading/trailing
s.strip(chars) '...test!!'.strip('.!') 'test'
characters specified in chars.

Splits the string into a list of ['apples',


s.split(sep) substrings using sep as the 'apples,oranges,bananas'.split(',') 'oranges',
delimiter. 'bananas']

Splits the string by any ['Hello,',


s.split() whitespace and discards s.strip().split() 'Python',
empty strings. 'World!']

Joins elements of a list into a


' '.join(['Python', 'is', 'fun'])<br/>'- 'Python is fun'
sep.join(list) single string, with sep as the
'.join(['a','b','c']) <br/> 'a-b-c'
separator.

s.replace(old, Replaces all occurrences of ' Hello, Python


s.replace('World', 'Universe')
new) substring old with new. Universe! '

6. String "Type" Checking (Boolean Methods)

These methods check for certain character types and return True or False.

Returns True if all


Method characters in the Example Result
string are...

s.startswith(prefix ...if the string begins


s.strip().startswith('Hello') True
) with prefix.

...if the string ends


s.endswith(suffix) s.strip().endswith('!') True
with suffix.

...alphanumeric
(letters a-z and
'Python3'.isalnum()<br/>'Python True<br/>Fals
s.isalnum() numbers 0-9) and
3'.isalnum() e
the string is not
empty.

...alphabetic (letters
True<br/>Fals
s.isalpha() a-z) and the string is 'Python'.isalpha()<br/>'Python3'.isalpha()
e
not empty.
...digits (0-9) and the True<br/>Fals
s.isdigit() '12345'.isdigit()<br/>'123a'.isdigit()
string is not empty. e

True<br/>Fals
s.islower() ...lowercase letters. 'python'.islower()<br/>'Python'.islower()
e

True<br/>Fals
s.isupper() ...uppercase letters. 'PYTHON'.isupper()<br/>'Python'.isupper()
e

...whitespace
True<br/>Fals
s.isspace() characters (space, ' '.isspace()<br/>' a '.isspace()
e
tab, newline).

...in title case (first


s.istitle() letter of each word 'Hello World'.istitle() True
is uppercase).

7. String Formatting

Used to embed variables and expressions inside strings.

Method Description Example Result

Prefix the string with f and place name = 'Alice'<br/>age = 'Name:


f-Strings (Modern &
variables/expressions inside curly 30<br/>f'Name: {name}, Age: Alice, Age:
Recommended)
braces {}. {age}' 30'

Call the .format() method on the name = 'Bob'<br/>'Hello, 'Hello,


.format() Method
string, using {} as placeholders. {}'.format(name) Bob'

% Operator (Old Uses %s (string), %d (integer), %f name = 'Charlie'<br/>"Hello, 'Hello,


Style) (float) as placeholders. %s" % name Charlie'

Python String Operators and Operator Precedence


These are the built-in operators that can be used directly with string objects.

Operato
Name Description Example Result
r

Joins two or more strings


+ Concatenation together to create a new 'Python' + ' ' + 'is fun' 'Python is fun'
string.

Repeats a string a specified


* Repetition number of times to create a 'Go! ' * 3 'Go! Go! Go! '
new string.

[] Indexing Accesses a single character s = 'Python'<br/>s[0] 'P'<br/>'n'


from the string at a specific <br/>s[-1]
zero-based index.

Extracts a portion (a
[:] Slicing s = 'Python'<br/>s[2:5] 'tho'
substring) of the string.

Returns True if a character


'thon' in 'Python'<br/>'x'
in Membership or substring exists within True<br/>False
in 'Python'
the string.

Returns True if a character 'Java' not in


Non-
not in or substring does not exist 'Python'<br/>'Py' not in True<br/>False
Membership
within the string. 'Python'

Formats a string using


Formatting 'Name: %s, Age: %d' % 'Name: Alice,
% placeholders like %s (string)
(Old) ('Alice', 30) Age: 30'
and %d (integer).

Operator Precedence

Operator precedence determines the order in which operations are performed in a complex
expression. Operations with higher precedence are performed before those with lower
precedence.

The following table shows Python's operator precedence from highest to lowest, focusing on the
operators relevant to strings.

Precedence
Operator(s
(Highest to Description Example Expression & Evaluation
)
Lowest)

Parentheses ('Hello' + ' ' + 'World') * 2<br/>Evaluates to:


1 (Highest) ()
(Grouping) 'Hello World' * 2 → 'Hello WorldHello World'

'Python'[1].upper()<br/>Evaluates to:
2 s[i], s[i:j] Indexing and Slicing
'y'.upper() → 'Y'

Repetition (same as 'A' + 'B' * 3<br/>* is higher than +. Evaluates to:


3 *
Multiplication) 'A' + 'BBB' → 'ABBB'

Concatenation 'A' + 'B' + 'C'<br/>Evaluates left to right: 'AB' +


4 +
(same as Addition) 'C' → 'ABC'

'a' in 'abc' and 'd' not in 'abc'<br/>Evaluates to:


5 in, not in Membership tests
True and True → True

not 'a' in 'xyz'<br/>Evaluates to: not False →


6 not Logical NOT
True

'a' in 'ax' and 'b' in 'by'<br/>Evaluates to: True


7 and Logical AND
and True → True
'a' in 'x' or 'b' in 'by'<br/>Evaluates to: False or
8 (Lowest) or Logical OR
True → True

Key Takeaways on Precedence:

 Repetition over Concatenation: The repetition operator (*) has higher precedence than the
concatenation operator (+), just like multiplication has higher precedence than addition in
mathematics.

o 'A' + 'B' * 3 is evaluated as 'A' + ('B' * 3).

 When in Doubt, Use Parentheses: If you are unsure about the order of evaluation or want
to make your code more readable, use parentheses () to explicitly group operations.

o For example, ('A' + 'B') * 3 is much clearer and yields a different result ('ABABAB')
than the example above.

Python Operators and its Precedence


Part 1: Python Operators by Category

This table groups the operators by their function, explaining what they do with a clear example.
Let's assume the following variables for the examples:
a = 10, b = 4, x = [1, 2, 3], y = [1, 2, 3]

Operato
Category Name Example Result & Explanation
r

Arithmetic + Addition a+b 14 (Adds values)

- Subtraction a-b 6 (Subtracts values)

* Multiplication a*b 40 (Multiplies values)

/ Division a/b 2.5 (Performs float division)

2 (Performs integer division, discards


// Floor Division a // b
remainder)

% Modulus a%b 2 (Returns the remainder of a division)

** Exponentiation a ** b 10000 (Raises a to the power of b)

Comparison == Equal to a == 10 True

!= Not equal to a != b True

> Greater than a>b True

< Less than a<b False

>= Greater than or a >= 10 True


equal to
Less than or equal
<= b <= 5 True
to

(a > 5) and (b
Logical and Logical AND True (Both conditions must be true)
< 5)

(a < 5) or (b < True (At least one condition must be


or Logical OR
5) true)

not Logical NOT not (a > 5) False (Inverts the boolean value)

Assignment = Assign c=5 c is now 5

+= Add and assign a += b a becomes 14 (Same as a = a + b)

-= Subtract and assign a -= b a becomes 6 (Same as a = a - b)

*= Multiply and assign a *= b a becomes 40 (Same as a = a * b)

Membershi
in In 2 in x True (Checks if a value is in a sequence)
p

True (Checks if a value is not in a


not in Not in 4 not in x
sequence)

False (Checks if two variables are the


Identity is Is x is y
same object in memory)

True (Checks if two variables are


is not Is not x is not y
different objects)

Bitwise & Bitwise AND a&b 0 (Binary 1010 & 0100 = 0000)

` ` Bitwise OR `a

^ Bitwise XOR a^b 14 (Binary 1010 ^ 0100 = 1110)

~ Bitwise NOT ~a -11 (Inverts all bits, ~x is -x-1)

<< Left Shift a << 1 20 (Shifts bits left, same as a * 2**1)

>> Right Shift a >> 1 5 (Shifts bits right, same as a // 2**1)

Part 2: Operator Precedence in Python

This table lists Python operators from highest precedence (evaluated first) to lowest precedence
(evaluated last). Operators in the same box have the same precedence and are evaluated from left
to right (unless stated otherwise).

Precedence Operator(s) Description Example & Evaluation Flow


(Highest to Lowest)
1 (Highest) () Parentheses / Grouping (2 + 3) * 4 → 5 * 4 → 20

Function Calls, Slicing,


2 f(...) x[...] x.attr 'hello'.upper() → 'HELLO'
Attribute Access

Exponentiation (Right-
3 ** 2 ** 3 ** 2 → 2 ** 9 → 512
associative)

Unary Plus, Unary Minus,


4 +x, -x, ~x -5 ** 2 → -(5**2) → -25
Bitwise NOT

Multiplication, Division,
5 *, /, //, % 2 + 3 * 4 → 2 + 12 → 14
Floor Division, Modulus

6 +, - Addition and Subtraction 10 - 4 * 2 → 10 - 8 → 2

7 <<, >> Bitwise Shifts 10 >> 1 + 1 → 10 >> 2 → 2

8 & Bitwise AND 5&3+2→5&5→5

9 ^ Bitwise XOR 5^3&2→5^2→7

10 ` ` Bitwise OR

in, not in, is, is not, <, Comparisons, Identity, 5 > 3 == True → True ==
11
<=, >, >=, !=, == Membership True → True

not 5 > 3 → not True →


12 not Logical NOT
False

True or False and False →


13 and Logical AND
True or False → True

5 > 10 or 3 > 1 → False or


14 (Lowest) or Logical OR
True → True

The Golden Rule of Precedence

When in doubt, use parentheses ().

Using parentheses makes your code easier to read and guarantees the operations are performed in
the order you intend, regardless of the underlying precedence rules.

Example:

 Unclear: 5 + 3 * 10 / 2

 Clear: 5 + ((3 * 10) / 2)

Introduction to Formatted Printing


 Formatted printing (or string formatting) is the process of embedding variables,
values, or expressions inside a string. Python provides three main ways to do this.
 Let's define some sample variables to use in our examples:
name = "Alice"
age = 30
pi = 3.14159

 1. Comparison of Formatting Methods
 This table provides a high-level overview of the three primary methods, comparing
their syntax and key characteristics.

Method Syntax Key Features When to Use


Fastest, most readable,
f-Strings
and concise. The default, recommended
(Formatted
f"text {variable} text" Expressions inside {} choice for all new Python
String
are evaluated at runtime. code.
Literals)
Requires Python 3.6+.
Very powerful and When you need to work with
flexible. Separates the template strings defined
.format() "text {} template string from the separately from the data
Method text".format(variable) data being inserted. (e.g., in configuration files)
Works in Python 2.6+ or for compatibility with
and 3.x. older Python versions.
Oldest method,
inspired by C's printf.
Legacy code. It's important
Can be less readable and
% Operator "text %s text" % to recognize it, but you
prone to errors if types
(Old Style) (variable,) should avoid using it for new
don't match the format
projects.
specifier (e.g., %s vs.
%d).

 2. Basic Usage Examples
 This table shows a direct, side-by-side comparison of how to perform a simple
substitution with each method.

Method Example Result


f-String print(f"Name: {name}, Age: {age}") Name: Alice, Age: 30
.format() print("Name: {}, Age: {}".format(name, age)) Name: Alice, Age: 30
print("Name: {n}, Age: {a}".format(n=name, a=age)) Name: Alice, Age: 30
% Operator print("Name: %s, Age: %d" % (name, age)) Name: Alice, Age: 30

 3. Advanced Formatting (The Format Specification Mini-Language)
 The real power of string formatting comes from the "mini-language" you can use
inside the placeholders. The syntax is nearly identical for f-strings and the .format()
method.
 General Syntax: {value:specifier}
 The following table details common formatting specifiers.
Syntax (f-
Feature string & Example (using f-string) Result
.format())
< (Left)
<br/> > 'Alice '<br/>'
Alignmen f"'{name:<10}'"<br/>f"'{name:>10}'"<br/>f"'{nam
(Right) Alice'<br/>' Alice
t e:^10}'"
<br/> ^ '
(Center)
Padding
fill_char +
with a
align + f"'{name:*^10}'" '**Alice***'
Characte
width
r
Controlli
.[precision
ng
]f for f"Pi is {pi:.2f}" "Pi is 3.14"
Decimal
floats
Places
Number
Padding
0 + width f"Item ID: {age:05}" "Item ID: 00030"
(with
Zeros)
Thousan
ds
, num = 1234567<br/>f"{num:,}" "1,234,567"
Separato
r
Percentag
.% ratio = 0.85<br/>f"{ratio:.1%}" "85.0%"
e
d
Displayin
(Decimal)
g as
<br/> b "11111111"<br/>"
different num = 255<br/>f"{num:b}"<br/>f"{num:x}"
(Binary) ff"
number
<br/> x
systems
(Hex)
+ for
both, - for
Forcing a
negative f"{age:+}"<br/>f"{-age:+}" "+30"<br/>"-30"
Sign (+/-)
only
(default)
Using Any valid
expressio Python
"In 5 years, Alice
ns (f- expressio f"In 5 years, {name} will be {age + 5}."
will be 35."
strings n inside
only) {}

 Summary: Which Method Should You Use?

Method Recommendation
f-Strings Use this by default. It is the most modern, readable, and performant option for
Python 3.6 and newer.
Use this if you need compatibility with older Python versions (3.0-3.5) or if you
.format() have a specific use case where the format string is stored separately from the
data.
% Avoid for new code. Only use it when you are maintaining or updating old code
Operator that already relies on it.

You might also like