Download presentation
Presentation is loading. Please wait.
1
CSE 231 Lab 3
2
Topics to cover Strings Basics String Slicing String Comparison
String Methods Patterns to Build Strings String Formatting
3
Strings basics review H e l o W r d 1 2 3 4 5 6 7 8 9 10
>> input_str = ‘Hello World’ H e l o W r d 1 2 3 4 5 6 7 8 9 10 >> print(input_str)? >> print(type(input_string))? >> print(len(input_str))? >> print(input_str[1])? Hello World <class 'str'> 11 e
4
Strings basics review H e l o W r d 1 2 3 4 5 6 7 8 9 10 -11 -10 -9 -8
>> input_str = ‘Hello World’ H e l o W r d 1 2 3 4 5 6 7 8 9 10 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 >> print(input_str[-1])? d >> print(input_str[-5])? W >> print(input_str[-10])? e
5
Slicing Start end input_str[ : ] Does not include Includes
6
>> input_str = ‘Hello World’
1 2 3 4 5 6 7 8 9 10 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 >> print(input_str[6:10])? Worl >> print(input_str[6:11])? World >> print(input_str[6:])? World Hello >> print(input_str[:5])? Hello >> print(input_str[0:5])? >> print(input_str[3:-2])? lo Wor
7
Extended Slicing H e l o W r d 1 2 3 4 5 6 7 8 9 10 -11 -10 -9 -8 -7
>> input_str = ‘Hello World’ H e l o W r d 1 2 3 4 5 6 7 8 9 10 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 >> print(input_str[::2])? HloWrd >> print(input_str[::-2])? drWolH >> print(input_str[1::2])? el ol
8
String comparison ‘a’ < ‘b’ ‘hi’ > ‘hello’ ASCII table
9
String Methods Methods are like functions but specific to certain classes .isupper() #checks if entire string is upper case .isdigit() #checks if entire string is a digit (number) .isalpha() #checks if entire string is all letters(word) .lower() #converts string to all lower case .find(ch) #returns the first index where ch is found, -1 if not .rfind(ch) #returns the last index where ch is found, or -1 if not .replace(old, new) #returns a new string where all occurrences of old substring is replaced with new substring.
10
Patterns to build string
Ints: x = 0 # initialize at zero x += 1 # increment the counter Strings: s = ‘’ # initialize with empty string s += ch # concatenate characters
11
String Formatting price = 2000 str1= ‘Price’
print('{ } is ${ }'.format(str1, price)) Price is $2000 #What gets printed?
12
String Formatting {:[align] [minimum_width] [.precision] [descriptor]}
>> price = 2000 >> print('{ }'.format(price)) {:[align] [minimum_width] [.precision] [descriptor]} >> print('{:>10,d}'.format(price)) 2,000 |__________| 10 spaces #What gets printed?
13
String Formatting
14
Enumerate: Alphabet = ‘michigan’ for c, value in enumerate(Alphabet):
print(c, value) 2 m 3 i 4 c 5 h 6 i 7 g 8 a 9 n Alphabet = ‘michigan’ for c, value in enumerate(Alphabet, 2): print(c, value)
15
String Formatting s : string d : decimal integer
f : floating point decimal Demo: lab03.pre-lab.part_D.py
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.