0% found this document useful (0 votes)
4 views17 pages

Strings in Python - Jasmin

strings in python for gtu

Uploaded by

labkirtan9
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)
4 views17 pages

Strings in Python - Jasmin

strings in python for gtu

Uploaded by

labkirtan9
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/ 17

Strings in Python

Prepared by Patel Jasmin

Table of Contents
1. String Basics ........................................................................................................................................................ 2
2. String Operations ............................................................................................................................................. 2
Concatenation....................................................................................................................................................... 2
Repetition ............................................................................................................................................................... 3
Check String .......................................................................................................................................................... 3
Conversion ............................................................................................................................................................. 4
3. Indexing and Slicing ....................................................................................................................................... 6
Strings are Arrays................................................................................................................................................. 6
Slicing ....................................................................................................................................................................... 6
4. String Methods .................................................................................................................................................. 7
Count........................................................................................................................................................................ 7
title(), lower(), upper(), capitalize() ................................................................................................................ 8
find(), rfind(), index(), rindex() ......................................................................................................................... 8
strip(), lstrip(), rstrip() .......................................................................................................................................... 9
replace(), split() .................................................................................................................................................. 10
isalpha(), isalnum(), isdecimal(), isdigit() .................................................................................................. 10
format()................................................................................................................................................................. 12
5. String Formatting .......................................................................................................................................... 12
Formatting with % Operator ........................................................................................................................ 12
Formatting with format() method .............................................................................................................. 13
String Formatting with F-Strings ................................................................................................................ 13
6. Iteration Approaches ................................................................................................................................... 14
For Loop ............................................................................................................................................................... 14
While Loop .......................................................................................................................................................... 15
Enumerate ........................................................................................................................................................... 15
List comprehensions........................................................................................................................................ 16
Reversed Iteration ............................................................................................................................................ 16
Using iter() and next() ..................................................................................................................................... 16

1|Page
1. String Basics
Strings in Python are ordered sequences of characters. They are immutable and can
be created using single, double, or triple quotes.

There is no difference in single and double quotes in string in python.

You can use quotes inside a string, as long as they don't match the quotes
surrounding the string.

print("It's alright")

print("His name is 'Adam'")

print('Her name is "Nita"')

2. String Operations
String operations include concatenation, repetition, indexing, slicing, and
determining the length of a string.

Concatenation
We can concatenate string using ‘+’ operator. Note that there will not be any space
in between.

We cannot concatenate string with other objects using + operator.

We can also concatenate strings using ‘+=’ operator.

2|Page
Putting two or more quoted strings in a line results in concatenation (also no space
between).

By using ‘,’ operator we can get one space between strings.

Repetition
We can multiply (repeat) string using * operator.

Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.

To check if a certain phrase or character is present in a string, we can use the


keyword “in”. It returns Boolean value.

3|Page
Use it in an if statement :

To check if a certain phrase or character is NOT present in a string, we can use the
keyword “not in”.

Conversion
In python, Strings can be converted to different data types and vice versa using built-
in functions.

Use int() to convert a string representing an integer to an integer.

Use float() to convert a string representing a float to a float.

Convert strings to Booleans manually since Python does not directly convert strings
like "True" or "False".

To convert a string to NoneType, use a conditional check.

4|Page
Use complex() to convert a string representing a complex number to a complex
type.

You can use eval() to convert a string representing a list back to a list.

Using eval() we can convert a string to data types like List, Tuple, Set, Dictionary.

For converting from any other data type to string we can use ‘str()’ function same as
we have used others above.

5|Page
3. Indexing and Slicing

Strings are Arrays


Like other programming languages, strings in python are arrays of bytes
representing unicode characters.

However, Python does not have a character data type, a single character is simply a
string with a length of 1.

Square brackets (Access operator ‘[]’) can be used to access elements of the string.

Slicing
Using colon ‘:’ operator we can select range of characters in string, it’s called slicing.

• Syntax : x = 'our string'

subx1 = x[startindex]

subx2 = x[startindex : endindex]

subx3 = x[startindex : endindex : steps]

The startindex, endindex, and steps values must all be integers, It extracts the
substring from startindex till endindex (not including endindex) with steps defining
the increment of index.

Using negative indexes selects string from the end. i.e. -1 selects last character of
string.

=> Rules of indexing and slicing :

1. Returned string contains all the characters from start to end but excluding end
(start to end - 1).
2. If start not given, then it will start from index 0.

6|Page
3. If end not given, then it will continue until the end of the string.
4. If start or end are specified as a negative number, it selects the index from end
where -1 is the last character.
5. Positive step means normal order and negative step means reversed order of
string. i.e. string[2 : 7 : -1] here step is -1 so its 1 step at a time in reversed
order.

Here are some examples to get more clarity.

4. String Methods
Python provides a variety of built-in methods for string manipulation.

Note: All string methods return new values. They do not change the original string.

len() is not a string function but we can use this method to get the length of string.

Count
count() method will return the number of times a specified value occurs in a string.

- Syntex: string.count(substring, start= …., end= ….)

7|Page
Here Start and End are optional.

title(), lower(), upper(), capitalize()


title(), lower(), upper() will returns first character of each word capitalized, lower
case and upper case string respectively. Where capitalize() will only convert first
character of whole string into capital.

find(), rfind(), index(), rindex()


The find() method returns the lowest index or first occurrence of the substring and
rfind() method finds the last occurrence of the substring if it is found in a given
string.

- Syntax: string.find(value, start, end) (Start and End are optional)


- Same for rfind() method

In below example, it will search ‘e’ only between 5 to 10 (10 excluded) (to End -1).

The index() method finds the first occurrence of the specified value and the rindex()
method finds the last occurrence of the specified value. Both method raises an
exception if the value is not found.

8|Page
- Syntax: string.index(value, start, end) (Start and End are optional)
- Same syntax for rindex() method

The index() method is almost the same as the find() method, the only difference is
that the find() method returns -1 where the index() method raises an exception if the
value is not found. Same with rindex() and rfind() as well. (See example below)

strip(), lstrip(), rstrip()


The strip() method removes any whitespace from the beginning or the end.

- Syntax : string.strip(characters)

The rstrip() method removes specified characters (whitespace by default) from the
end and the lstrip() method removes any leading characters(from the start).

9|Page
replace(), split()
The replace() method replaces a string with another string.

The split() method splits the string into substrings if it finds instances of the
separator and returns list of that substrings.

- Notice the space before ‘ World!’ in output list.

isalpha(), isalnum(), isdecimal(), isdigit()


isalnum() method will return true if all the characters in the string are alphanumeric
(i.e either alphabets or numeric).

isalpha() and isnumeric() will return true if all the characters in the string are only
alphabets and numeric respectively.

10 | P a g e
isdecimal() will return true if all the characters in the string are decimal.

The isdigit() method checks if all characters in the string are digits.

Summary of Differences:

• isalpha(): Strictly checks for alphabetic letters.

• isalnum(): Allows both letters and digits (no spaces or symbols).

• isdecimal(): Checks for basic decimal digits (0-9), most restrictive among
digit-related methods.

• isdigit(): Checks for all digit characters, including those from other numeral
systems (e.g., superscripts).

11 | P a g e
• isnumeric(): Broadest scope, checks for all numeric characters, including
fractions, Roman numerals, and numerals in other languages.

format()
The format() method formats the specified value(s) and insert them inside the
string's placeholder.

The placeholders can be identified using named indexes {price}, numbered indexes
{0}, or even empty placeholders { }.

More examples of format() method:

Please refer either of the below pages for more methods:

- https://www.w3schools.com/python/python_strings_methods.asp
- https://www.geeksforgeeks.org/python-string-methods/?ref=lbp

5. String Formatting
String formatting in Python allows for the insertion of values into strings.

Formatting with % Operator


Formatting with % Operator is the oldest method of string formatting. Here we use
the modulo % Operator. The modulo % is also known as the “string-formatting
operator”.

- The %5.4f format specifier is used to format a floating-point number with a


minimum width of 5 and a precision of 4 decimal places.

12 | P a g e
Formatting with format() method
We have seen this in String Methods section.

Syntax: { }.format(value)

value: Can be an integer, floating point numeric constant, string, characters or even
variables.

Return type: Returns a formatted string with the value passed as parameter in the
placeholder position.

Float Precision with the .format() Method.

Here is the example using Float Precision.

String Formatting with F-Strings


To create an f-string, prefix the string with the letter “f”. The string itself can be
formatted in much the same way that you would with str. format().

13 | P a g e
In below code, an anonymous lambda function is defined using lambda x: x*2. Here,
this function doubles the given value.

Float precision in the f-String Method.

- Syntax: {value:{width}.{precision}}

Printing Braces using f-string.

6. Iteration Approaches

For Loop
Using a for loop is a straightforward way to iterate over each character in a string.

Output :

14 | P a g e
While Loop
A while loop can also be used for iteration by maintaining an index counter.

Output :

Enumerate
Using enumerate allows you to get both the index and the character at the same
time.

Output :

15 | P a g e
List comprehensions
List comprehensions provide a concise way to create lists by iterating over a string.

Output :

Reversed Iteration
You can iterate over a string in reverse using the reversed() function.

Output :

Using iter() and next()


You can create an iterator from a string using iter() and get each character using
next().

16 | P a g e
Output :

In above code, try – except block is similar to try – catch block we have studied in
Java.

17 | P a g e

You might also like