Python 4
Python 4
• 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
• Output
• Hello
Hello
Assign String to a Variable
• Output
• Hello
Multiline Strings
• 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
• Example
• Get the characters from the start to position 5
(not included):
• b = "Hello, World!"
print(b[:5])
• Output
• Hello
Slice To the End
• Example
• The replace() method replaces a string with
another string:
• a = "Hello, World!"
print(a.replace("H", "J"))
• Output
• Jello, World!
Split String
• 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