0% found this document useful (0 votes)
25 views30 pages

3 OperationsWithString

This document discusses various string operations and methods in Python. It covers indexing and accessing characters in strings, basic operations like length, finding indexes, checking if a string starts or ends with something. It also covers counting characters, slicing strings, formatting strings using %, .format(), and f-strings, transforming case, splitting strings, and replacing/escaping characters. Exercises are provided to demonstrate string formatting and operations.

Uploaded by

psiharisthanos
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)
25 views30 pages

3 OperationsWithString

This document discusses various string operations and methods in Python. It covers indexing and accessing characters in strings, basic operations like length, finding indexes, checking if a string starts or ends with something. It also covers counting characters, slicing strings, formatting strings using %, .format(), and f-strings, transforming case, splitting strings, and replacing/escaping characters. Exercises are provided to demonstrate string formatting and operations.

Uploaded by

psiharisthanos
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/ 30

String operations with

Python
Sokratis Sofianopoulos
Basic String Operations
Indexing strings

• Each character of a string can be accessed by a corresponding index


number, starting with the index number 0
astring = "Hello world!"
print(astring[0])
• We can also use negative indexes to access a character starting from the
end of the string, with the first index being -1 and corresponding to the last
char.
print(astring[-1])
Basic String Operations

• Strings are bits of text. They can be defined as anything between quotes:
astring = "Hello world!"
astring2 = 'Hello world!'
• Printing the length of a string
print(len(astring))
• Printing the location of the first occurrence of a character
print(astring.index("o"))

4
startswith and endswith

• This is used to determine whether the string starts with something or ends
with something, respectively
• print(astring.startswith("Hello"))
• This ill print True, as the string starts with "Hello“
• print(astring.endswith("World"))
• What will this print?

5
count

• If we want to count the number of times either one particular character or


a sequence of characters appear in a string, we can use str.count():
astring = "Hello world!"
print(astring.count("o"))
print(astring.count("h"))
print(astring.count("Hello"))

6
find

• str.find() returns the index a character or character sequence first occurs:


astring = "Hello world!"
print(astring.find("o"))
• If we want to see where the second sequence of "o" begins we pass a 2nd
parameter to the str.find() method that defines the index where the search
will start. So if we want to start counting at position 5:
print(astring.find("o", 5))
• We can also pass a third parameter to define the end index position of the
search
7
Exercise

In the string astring = "Hello world!" you need to find the index of the second
appearance of the "o" character. How can you do that if you only know that
there are two "o" characters in the string but you do not know the index of
the first character?

8
Solution

astring = "Hello world!"


print(astring.find("o", astring.find("o")+1))

9
isdigit() and isalpha()

• str.isdigit() returns true if the character is a digit


• str.isalpha() returns true if the character is a letter
• You can apply both functions in either a single character or a string

10
String replacing

• The method replace() returns a copy of a string where the occurrences of


the initial string have been replaced with the new
• Syntax: str.replace(old, new[, max]), where:
• old: This is old substring to be replaced
• new: This is new substring, which would replace old substring
• max: If this optional argument max is given, only the first count
occurrences are replaced
• The method returns a copy of the string with all occurrences of substring
old replaced by new

11
String replace example

initial_string = "this is string example...!!! this is really string"


new_string = initial_string.replace("is", "was")
new_string = initial_string.replace("is", "was", 3)

12
Getting a slice of a string

astring = "Hello world!"


print(astring[3:7])
• If you just have one number in the brackets, it will give you the single character at that
index
• If you leave out the first number but keep the colon, it will give you a slice from the start
to the number you left in
• If you leave out the second number, if will give you a slice from the first number to the
end
• You can even put negative numbers inside the brackets. They are an easy way of starting
at the end of the string instead of the beginning. This way, -3 means "3rd character from
the end"

13
Extended slice syntax

astring = "Hello world!"


print(astring[3:7:1])
• This prints the characters of string from 3 to 7 moving 1 character at a time
• The general form is [start:stop:stride]
• You can use this to reverse a string
print(astring[::-1])

14
Transforming to uppercase or lowercase

• You can transform a string to upper or lower casing


print(astring.upper())
print(astring.lower())

15
Splitting a string

astring = "Hello world!"


tokens = astring.split(" ")
• This splits the string into a bunch of strings grouped together in a list (we
will see lists later)
• Since this example splits at a space, the first item in the list will be "Hello",
and the second will be "world!"
• This is a simple tokenizer, which is an important tool for Natural Language
Processing

16
String Formatting
String formatting

In Python there are three ways to format your strings:


• C-style String Formatting using the % Operator
• New Style String Formatting using str.format
• f-Strings
• In the following examples we will be using the formatted string
inside print statements (so as to see the result) but the

18
C-style String Formatting

• Python uses C-style string formatting to create new, formatted string


• The "%" operator is used to format a set of variables enclosed in a "tuple"
(a fixed size list), together with a format string, which contains normal text
together with "argument specifiers", special symbols like "%s" and "%d"

name = "Sokratis"
print("Hello, %s!" % name)

19
C-style String Formatting (cont.)

• To use two or more argument specifiers, use a tuple (parentheses):


name = "Sokratis"
lastname = "Sofianopoulos"
print("%s %s" % (name, lastname))
• To print numbers:
labname = "Lab"
labnumber = 510
day="Monday"
print("Lecture is at %s %d every %s " % (labname, labnumber, day))
20
Exercise
• Create a string, an integer, and a floating-point number
• The string should be named mystring and should contain the word
"hello"
• The floating-point number should be named myfloat and should contain
the number 10.0
• The integer should be named myint and should contain the number 20
• You can use the following code to test your code

21
Solution

# testing code
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % myint)

22
Basic argument specifiers

• %s
• String (or any object with a string representation, like numbers)
• %d
• Integers
• %f
• Floating point numbers
• %.<number of digits>f
• Floating point numbers with a fixed amount of digits to the right of the dot
• %x/%X
• Integers in hex representation (lowercase/uppercase)
23
New Style String Formatting

• The new style string formatting gets rid of the %-operator


• Formatting is now handled by calling .format() on a string
• Positioning of the variable in the string is done using the {} characters
name = "Sokratis"
print("Hello, {}!".format(name))
• You can also use more than one variable
lbnm = "Lab"
lbnmbr = 510
day="Monday"
print("Lecture is at {l} {n} every {d}".format(l=lbnm, n=lbnmbr, d=day))

24
f-Strings

• Python 3.6 added a new formatting approach: formatted string literals or f-strings
• This new way of formatting strings lets you use embedded Python expressions
inside string constants
• Example:
name = "Sokratis"
print(f"Hello, {name}!")

• This prefixes the string constant with the letter f


• With this formatting syntax you can embed arbitrary Python expressions

25
f-String examples

labname = "Lab"
labnumber = 510
day="Monday"
print(f"Lecture is at {labname} {labnumber} every {day}")

26
Comparing with a traditional string creation

a=5
b = 10
message = f'Five plus ten is {a + b} and not {2 * (a + b)}.'

This is the same as:


a=5
b = 10
message = 'Five plus ten is ' + str(a + b) + ' and not '+str(2 * (a + b))+'.'

27
Escaping characters when using f-Strings

• Make sure you are not using the same type of quotation mark on the outside of
the f-string as you are using in the expression (mix double and single ones)
• If you find you need to use the same type of quotation mark on both the inside
and the outside of the string, then you can escape with the backslash (\)
character:
name = "Sokratis"
print(f"Hello, \"{name}\"!")
• You can work around this by evaluating the expression beforehand and using the
result in the f-string:
name = '"Sokratis"'
print(f"Hello, {name}!")
28
Exercises
1. Write the following message combining three variables using f-String:

Hello "NAME LASTNAME". Your current balance is 53.44 €

2. Using two variables a and b write the following message using f-String:

A in the power of B is AB

29
Solution

1. name = "Sokratis"
lname = "Sofianopoulos"
balance = 53.44
print(f'Hello "{name} {lname}". Your current balance is {balance}€')

2. a = 2
b=3
print(f"{a} in the power of {b} is {a**b}")
30

You might also like