Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python 4

The document provides an overview of Python casting, string manipulation, and formatting. It explains how to cast variables to different types using constructor functions like int(), float(), and str(), and covers string operations such as slicing, modifying, concatenating, and formatting strings. Examples are provided to illustrate each concept, demonstrating how to work with strings effectively in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python 4

The document provides an overview of Python casting, string manipulation, and formatting. It explains how to cast variables to different types using constructor functions like int(), float(), and str(), and covers string operations such as slicing, modifying, concatenating, and formatting strings. Examples are provided to illustrate each concept, demonstrating how to work with strings effectively in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Python Casting

• Specify a Variable Type


• There may be times when you want to specify
a type on to a variable.
• This can be done with casting.
• Python is an object-orientated language, and as
such it uses classes to define data types,
including its primitive types.
• Casting in python is therefore done using constructor
functions:
• int() - constructs an integer number from an integer
literal, a float literal (by removing all decimals), or a
string literal (providing the string represents a whole
number)
• float() - constructs a float number from an integer literal,
a float literal or a string literal (providing the string
represents a float or an integer)
• str() - constructs a string from a wide variety of data
types, including strings, integer literals and float literals
• Example
• Integers:
• x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

• Output
• 1
2
3
• Example
• Floats:
• x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

• Output
• 1.0
2.8
3.0
4.2
• Strings:
• x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

• Output
• s1
2
3.0
Strings

• Strings in python are surrounded by either


single quotation marks, or double quotation
marks.
• 'hello' is the same as "hello".
• You can display a string literal with the print()
function:
• Example
• print("Hello")
print('Hello')

• Output
• Hello
Hello
Assign String to a Variable

• Assigning a string to a variable is done with the


variable name followed by an equal sign and the
string:
Example
• a = "Hello"
print(a)

• Output
• Hello
Multiline Strings

• You can use three double quotes:


• a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

• Output
• Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua
• Or three single quotes
• a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

• Output
• Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
Slicing Strings

• You can return a range of characters by using the


slice syntax.
• Specify the start index and the end index,
separated by a colon, to return a part of the string.
• Example
• Get the characters from position 2 to position 5
(not included):
• b = "Hello, World!"
print(b[2:5])
• Output
• llo
Slice From the Start

• Example
• Get the characters from the start to position 5
(not included):
• b = "Hello, World!"
print(b[:5])

• Output
• Hello
Slice To the End

• By leaving out the end index, the range will go


to the end:
• Example
• Get the characters from position 2, and all the
way to the end:
• b = "Hello, World!"
print(b[2:])
• Output
• llo, World!
Negative Indexing

• Use negative indexes to start the slice from the


end of the string: Example
• Get the characters:
• From: "o" in "World!" (position -5)
• To, but not included: "d" in "World!" (position
-2):
• b = "Hello, World!"
print(b[-5:-2])
• Output
• orl
Python - Modify Strings

• Python has a set of built-in methods that you


can use on strings.
• Upper Case
• Example
• The upper() method returns the string in upper
case:
• a = "Hello, World!"
print(a.upper())
• Output
• HELLO, WORLD!
• Lower Case
• Example
• The lower() method returns the string in lower
case:
• a = "Hello, World!"
print(a.lower())
• Output
• hello, world!
Remove Whitespace
• Whitespace is the space before and/or after the
actual text, and very often you want to remove
this space.
• Example
• The strip() method removes any whitespace
from the beginning or the end:
• a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
• Output

• Hello, World!
Replace String

• Example
• The replace() method replaces a string with
another string:
• a = "Hello, World!"
print(a.replace("H", "J"))

• Output
• Jello, World!
Split String

• The split() method returns a list where the text


between the specified separator becomes the
list items.
• Example
• The split() method splits the string into
substrings if it finds instances of the separator:
• a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
• Output
• ['Hello', ' World!']
Python - String Concatenation

• String Concatenation
• To concatenate, or combine, two strings you can
use the + operator.
• Example
• Merge variable a with variable b into variable c:
• a = "Hello"
b = "World"
c=a+b
print(c)
• Output
• HelloWorld
• Example
• To add a space between them, add a " ":
• a = "Hello"
b = "World"
c=a+""+b
print(c)

• Output
• Hello World
Python - Format - Strings

• String Format
• As we learned in the Python Variables chapter,
we cannot combine strings and numbers like
this:
• Example
• age = 36
txt = "My name is John, I am " + age
print(txt)
• Output
• Traceback (most recent call last):
File "demo_string_format_error.py", line 2,
in <module>
txt = "My name is John, I am " + age
TypeError: must be str, not int
• But we can combine strings and numbers by
using the format() method!
• The format() method takes the passed
arguments, formats them, and places them in
the string where the placeholders {} are:
• Example
• Use the format() method to insert numbers into
strings:
• age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
• Output
• My name is John, and I am 36
• The format() method takes unlimited number of
arguments, and are placed into the respective
placeholders:
• Example
• quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {}
dollars."
print(myorder.format(quantity, itemno, price))
• Output
• I want 3 pieces of item 567 for 49.95 dollars.
• Example
• quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0}
pieces of item {1}."
print(myorder.format(quantity, itemno, price))
• I want to pay 49.95 dollars for 3 pieces of item
567

You might also like