0% found this document useful (0 votes)
5 views33 pages

CS106-Week-04

The document outlines the CS106 course on Introduction to Computer Programming, focusing on user input and string methods in Python. It covers the use of the input() function, various string methods and functions, string slicing, and formatting techniques. Additionally, it includes examples and exercises for practical understanding of these concepts.

Uploaded by

Ahsan Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views33 pages

CS106-Week-04

The document outlines the CS106 course on Introduction to Computer Programming, focusing on user input and string methods in Python. It covers the use of the input() function, various string methods and functions, string slicing, and formatting techniques. Additionally, it includes examples and exercises for practical understanding of these concepts.

Uploaded by

Ahsan Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

CS106-

Introduction to
Computer
Programming
By: Dr. Abdus Salam
Abasyn University Peshawar
04
Week
CS106-Introduction to Computer Programming
07
Lecture
CS106-Introduction to Computer Programming
Topics to be covered

01 Getting user input


Getting user input in Python

02 String Method/Functions
Understanding the use of built-in Python String methods and
functions to perform different tasks. Index and Slice Strings.
Using the input()
Function
● The input() function allows user input. It takes a string
argument that it uses to prompt the user for this text.

● Syntax
input(prompt)

● Prompt: A String, representing a default message before the


input.
Using the input()
Function
# Example 1
# Use the prompt parameter to write a message before the input:
>>> x = input('Enter your name:’)
>>> print('Hello, ' + x)

Output:
Using the input()
Function
# Example 2
# Demonstrates getting user input
name = input("Hello. What's your name? ")
sal = input(“And What's your Salary? ")
print("Hi, my name is ", name ," and I am getting " , sal , “ salary")

Output:
String Method/Functions
Method Description
capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string


String Method/Functions
Method Description
index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable


String Method/Functions
Method Description
isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Converts the elements of an iterable into a string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value
String Method/Functions
Method Description
rfind() Searches the string for a specified value and returns the last position of where it was found

rindex() Searches the string for a specified value and returns the last position of where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string


String Method/Functions
Method Description
swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning
Example
s
Let’s see some examples to understand the
Python String Methods
Using String Functions
# Example 1
# The upper() method returns the string in upper case:
>>> a = "Hello, World!"
>>> print(a.upper())
HELLO, WORLD!

# Example 2
# The lower() method returns the string in lower case:
>>> a = "Hello, World!"
>>> print(a.lower())
hello, world!
Using String Functions
# Example 3
# The replace() method replaces a string with another string:
>>> a = "Hello, World!"
>>> print(a.replace("H", "J"))
Jello, World!

# Example 4
# The split() method returns a list where the text between the
specified separator becomes the list items.
>>> a = "Hello, World!"
>>> print(a.split(","))
['Hello', ' World!']
Using String Functions
# Example 5:
name = input("Hello. What's your name? ")
sal = input(“And What's your Salary? ")
print("Hi, my name is ", name.upper() ," and I am getting " ,sal, “
salary")
Practice & Homework

What is the output of the following expressions?

quote = "I think there is a world market for may


be five computers."
print("Original quote:")
print(quote)
print("\nIn uppercase:")
print(quote.upper())
print("\nIn lowercase:")
print(quote.lower())
print("\nAs a title:")
print(quote.title())
print("\nWith a minor replacement:")
print(quote.replace("five", "millions of"))
08
Lecture
CS106-Introduction to Computer Programming
Topics to be covered

01 String Slicing
Python String slicing is a way of creating a sub-string from a
given string.

02 String Format
String formatting allows you to create dynamic strings by combining
variables and values.
String Slicing
● In Python, a string is an ordered sequence of Unicode characters. Each
character in the string has a unique index in the sequence.
● The index starts with 0. First character in the string has its positional index
0. The index keeps incrementing towards the end of string.
● Python slicing can be done in two ways:

● Using a slice() method

● Using the array slicing [:: ] method


String Slicing
● Index tracker for positive and negative index:
● String indexing and slicing in python.
● The Negative comes into consideration when tracking the string in
reverse.
Example
s
Let’s see some examples to understand the
Python String Slicing Methods
Using String Slicing
# Example 1
# Python program to demonstrate string slicing:
>>> String = ‘HELLO PYTHON'
>>> s1 = slice(5)
>>> s2 = slice(1, 11, 3)
>>> s3 = slice(-1, -12, -2)
>>> print(String[s1])
>>> print(String[s2])
>>> print(String[s3])
HELLO
EOYO
NHY LE
Using String Slicing
# Example 2
# Python program to demonstrate string slicing using []:
>>> String = ‘HELLO PYTHON'
>>> print(String[1])
>>> print(String[:5])
>>> print(String[6:10])
>>> print(String[6:10:2])
E
HELLO
PYTH
PT
Using String Slicing
# Example 3
# Python program to demonstrate negative index string slicing:
>>> String = ‘HELLO PYTHON'
>>> print(String[-1])
>>> print(String[:-7])
>>> print(String[-6:-2])
>>> print(String[-4:-7:-2])
>>> print(String[-4:-7:-2])
N
HELLO
PYTH
TP
PT
Formatting
Strings
Python Built-in Methods
String Formatting
● String formatting is the process of applying a proper format to a given value
while using this value to create a new string through interpolation.

● Python has several tools for string interpolation that support many formatting
features. In modern Python, you’ll use f-strings or the .format() method most of the
time. However, you’ll see the modulo operator (%) being used in legacy code.

● String formatting can be applied using:


• Format strings using f-strings for eager interpolation
• Use the .format() method to format your strings lazily
• Work with the modulo operator (%) for string formatting
• Decide which interpolation and formatting tool to use
String Interpolation
●String interpolation involves generating strings by inserting other
strings or objects into specific places in a base string or template.

●For example:
# string interpolation using an f-string:
>>> name = ‘Abasyn University’
>>> print(‘Welcome to ' + x)
Welcome to Abasyn University
Using str.format() to Format
Strings
●The .format() method to format values during string interpolation.

●In this type of interpolation, a template string is defined in some


part of the code and then interpolate values in another part.

●For example:
# string interpolation using .format():
>>> sum_template = "{0} plus {1} is {2}"
>>> a = 5
>>> b = 10
>>> print(sum_template.format(a, b, a + b))
5 plus 10 is 15
Formatting Strings With %
●Strings in Python have a built-in operation that
can be accessed with the modulo operator
(%). This operator does positional and named
string interpolation.

●For example: ● For example:


# string interpolation using %: >>> print("%d" % 123.123) # As an integer
>>> name = “Abasyn University" 123
>>> print(“Welcome to %s" % name) >>> print("%o" % 42) # As an Octal
52
Welcome to Abasyn University >>> print("%x" % 42) # As a Hexadecimal
2a
>>> print("%e" % 1234567890) # In
scientific notation
1.234568e+09
Practic
e!
Practice, Practice & Practice
“Talk is cheap, show me the code.”

— Linus Torvalds

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy