0% found this document useful (0 votes)
12 views51 pages

Week 2 MAK

The document provides an introduction to string data in Python, covering standard data types, string creation, special characters, and various string operations such as concatenation, repetition, indexing, slicing, and methods. It explains the immutability of strings and includes examples of how to manipulate strings using built-in functions. Additionally, it presents exercises for practical application of the concepts discussed.

Uploaded by

nixak34028
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)
12 views51 pages

Week 2 MAK

The document provides an introduction to string data in Python, covering standard data types, string creation, special characters, and various string operations such as concatenation, repetition, indexing, slicing, and methods. It explains the immutability of strings and includes examples of how to manipulate strings using built-in functions. Additionally, it presents exercises for practical application of the concepts discussed.

Uploaded by

nixak34028
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/ 51

WEEK 2: STRING DATA

INS 107E Introduction to Programming Languages (Python)

26.02.2025
Dr. Merve AKBAŞ KAPLAN 1
Standard data types
• The data stored in memory can be of many types.
• For example, a person's age is stored as a numeric value and his or her address is stored as
alphanumeric characters. Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.
• Python has five standard data types :
• Numbers
• String
• List
• Tuple
• Dictionary ❑There are no type declarations in Python, the
syntax of the expressions you run determines the
types of objects you create and use. 2
What is a string?
• Strings are a collection of characters which are
stored together to represent arbitrary text inside a
python program.

• Python strings are categorized as immutable


sequences, meaning that the characters they contain
have a left-to-right positional order and that they
cannot be changed in-place.

• You can create a string constant inside a python


program by surrounding text with either;
➢ single quotes ('),
➢ double quotes ("),
➢ a collection of three of either types of quotes ('''
or """).
3
4
How to create a string constant and assign its value to a variable?

5
Please note new string type variables at Variable Explorer window

6
7
Short strings can also span several lines, if the last character on a line is a backslash:

8
9
10
11
12
Special characters
These characters help format text, insert special symbols, or control output behavior.

13
Special characters

14
Special characters
• \n => for a new line
• \t => for tab

TRY AT HOME
Input Output
para_str = """this is a long string that is made up of this is a long string that is made up of
several lines and non-printable characters such as several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed. TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within this within the brackets [
the variable assignment will also show up. ], or just a NEWLINE within
""" the variable assignment will also show up.
print (para_str)
15
Special characters
Input Output
Let's make use of raw string. print ('C:\\myfolder') C:\myfolder
We would put expression in
print (r'C:\\myfolder') C:\\myfolder
r'expression'as follows:

Input Output
>>> x = '\\r\\n\\t\\t\\t\\t' \r\n\t\t\t\t
>>> print(x)
>>> x = r'\r\n\t\t\t\t' \r\n\t\t\t\t
>>> print(x)
>>> x = ‘ \ra\nb\tc\td\te\tf'
>>> x ' \ra\nb\tc\td\te\tf'
>>> print(x) a
b c d e f
16
Functions for Strings
❑len is a function to count the number of list elements:
>>> s='abcdefgh' >>> s='abc de fgh'
>>> len(s) >>> len(s)
8 10
❑min, max functions: The ASCII Code is the comparison feature for min and
>>> s='abcdefgh' max functions for strings, not the location or indexing of
>>> min(s) the characters.
'a'
>>> max(s)
'h'
>>> s='abCdeFgh'
>>> min(s)
'C'
>>> max(s)
'h' 17
Functions for Strings

18
Functions for Strings

19
Built-in Functions

20
Built-in Functions

https://docs.python.org/3/library/functions.html
21
Membership (‘in’) operator

22
Str and repr functions

23
String operations: Concatenation

• The result of “adding” two strings


together is a new string which consists
of the original strings put together
• No space or other character is inserted
between concatenated strings. If you
want a space, you can simply add it
Input Output
code="INS107E" INS107EIntroduction to Prog. Lang.
lecture="Introduction to Prog. Lang."
print (code+lecture)
code="INS107E" INS107E Introduction to Prog. Lang.
lecture="Introduction to Prog. Lang."
print (code+ " " +lecture)
lecturecode= "INS107E" "Intro. to Prog. Lang." INS107EIntro. to Prog. Lang.
print (lecturecode) 24
String operations: Concatenation
• Python considers the type of an object when it tries to apply an operator, so
that if you try to concatenate a string and a number, you’ll have problems
• The number (x) must first be converted to a string before it can be
concatentated: the core function str() or repr()
Input Output
x=4/2 print ("The result is"+x)
print ("The result is "+x)
TypeError: must be str, not
float
x=4/2 The result is 2.0
print ("The result is
"+str(x))

25
String operations: Repetition
• The asterisk (*), when used between a string and an integer creates a new
string with the old string repeated by the value of the integer
• The order of the arguments is not important

Input Output
print('10'*10) 10101010101010101010
print(10*'10') 10101010101010101010
tenten='10'*10 10101010101010101010
print (tenten)
print('#' * 50) ##############################################
####
26
String operations: Repetition

Input Output
print('5' * 10) 5555555555
print(10 * '5') 5555555555
tenten='10'*10 10101010101010101010
print (tenten)
print('#' * 50) ###############################
###################
27
String operations: Indexing and Slicing
• To extract a single character from a string, follow the string with the index of the desired character
surrounded by square brackets ([ ]), remembering that the first character of a string has index zero.
• If the subscript you provide between the brackets is less than zero, python counts from the end of
the string, with a subscript of -1 representing the last character in the string.
alphabet="abcdefghijklmno"

String a b c d e f g h i j k l m n o

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Index
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

28
String operations: Indexing and Slicing

29
String operations: Indexing and Slicing

Input Output
alphabet="abcdefghijklmno" de
print (alphabet[3:5])

Space also counts

alphabet="abcd efghijklmno" d
print (alphabet[3:5])

alphabet="abcdefghijklmno"
dfh
print (alphabet[3:8:2])
30
String operations: Indexing and Slicing
• When a slice starts at the beginning of a string, or continues until the end, you can omit
the first or second index, respectively
Input Output
alphabet="abcdefghijklmno"

print (alphabet[3:]) defghijklmno

print (alphabet[:6]) abcdef

print (alphabet[:20]) abcdefghijklmno


31
String Methods

32
String operations: Methods

33
String operations: Methods

34
String Methods

>>> s='''This is a long string


... you can write
... as many lines as
... you wish.''‘
>>> s.splitlines()
['This is a long string', 'you can write', 'as many
lines as', 'you wish.']
>>> s.splitlines(s.count('\n'))
['This is a long string\n', 'you can write\n', 'as
many lines as\n', 'you wish.']

35
String Methods

36
String Methods

37
String Methods

38
String Methods
• Use of count, index, find, rfind, replace, translate methods
Input Output
astring = "Hello world!"
print(len(astring)) 12

astring = "Hello world!"


3
print(astring.count("l"))

astring = "Hello world!"


4
print(astring.index("o")) >>> s1="a+b+c+d"
astring = "Hello world!" >>> s2=s1.replace('+','*')
4 >>> print(s2)
print(astring.find("o"))
a*b*c*d
astring = "Hello world!"
7
print(astring.rfind("o"))
39
40
41
String operations: Methods

• Use of Justificaton and Case methods

42
String operations: Methods

• Use of Justificaton and Case methods

43
String operations: Methods

44
String operations: Methods

45
String operations: Methods

46
String operations: Methods

47
• translate() returns a copy of the string in which all characters
have been translated using table

48
• translate() returns a copy of the string in which all characters have been translated using table

>>> str='This is trial'


>>> str.translate(str.maketrans("i","I"))
'ThIs Is trIal'

>>> intab="tis"
>>> outtab="TIS"
>>> str="this is trial"
>>> trantab=str.maketrans(intab,outtab)
>>> print(str.translate(trantab))
ThIS IS TrIal 49
Exercises
1) Write a code that uses Sentence1 and Sentence2 and gives the following result: Python
World
Sentence1: Hello World Sentence2: Python is good
Hint: Use slicing and concatenation

2) Write a code for counting the number of occurrences of "day" in the given sentence.
Today is a good day. Better than yesterday.

3) Write a code which changes all letters to lowercase in the given sentence.
hElLo WorLd hello world
50
Exercises
4) Write a code which changes all occurrences of "s" to "$" in the given word.
businesses bu$ine$$e$

5) Write a code which changes all occurrences of "s" except the first to "$" in the given
word.
businesses busine$$e$
Hint: Use slicing and concatenation

51

You might also like