String seperti tuple, elemennya tidak bisa diganti/diassign
website = 'http://www.python.org'
website[-3:]
'org'
website[-3:]='com'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-d8a17dd95ce7> in <module> ----> 1 website[-3:]='com' TypeError: 'str' object does not support item assignment
format = "Hallo, %s. hari ini %s ya?"
isi = ('Mas','mendung')
print(format % isi)
Hallo, Mas. hari ini mendung ya?
Tanda %s adalah penentu konversi (conversion specifiers), menandai dimana nilai akan diisikan/disisipkan. "s" artinya bahwa nilai harus dikonversikan sebagai string
format = "Pi dengan 3 desimal angka di belakang koma: %.3f"
from math import pi
print(format % pi)
Pi dengan 3 desimal angka di belakang koma: 3.142
Modul string menawarkan cara lain untuk menformat nilai menggunakan fungsi Template, yang harus diimport terlebih dahulu
from string import Template
s = Template('Sekali $x, tetap $x!')
s.substitute(x='merdeka')
'Sekali merdeka, tetap merdeka!'
s = Template('A $thing must never $action')
d={}
d['thing']='gentleman'
d['action']='show his shocks'
s.substitute(d)
'A gentleman must never show his shocks'
'%s plus %s equals %s' %(1, 1, 2)
'1 plus 1 equals 2'
'%10f' %pi
' 3.141593'
'%10.2f' %pi
' 3.14'
'%.2f' %pi
'3.14'
'%.5s' %'Wiwit Suryanto'
'Wiwit'
Kita dapat memakai * sebagai pengatur lebar atau presisinya, dengan input nanti dibaca dari tuple
'%.*s' % (5,'Wiwit Suryanto')
'Wiwit'
Sebelum memberikan informasi lebar dan presisi dari sebuah bilangan, kita dapat mmeberi tanda, berupa nol, plus, minus atau kosong.
'%010.2f' % pi
'0000003.14'
'%-10.2f' %pi
'3.14 '
print(('% 5d' %10) + '\n' + ('% 5d' % -10))
10 -10
print(('%+5d' %10) + '\n' + ('%+5d' % -10))
+10 -10
width = input('Masukkan lebar tabel: ')
price_width = 10
item_width = int(width) - price_width
header_format = '%-*s%*s'
format = '%-*s%*.2f'
print('='*int(width))
print(header_format %(item_width,'Item',price_width,'Price'))
print('-'*int(width))
print(format %(item_width,'Apples',price_width,0.4))
print(format %(item_width,'Pears',price_width,0.5))
print(format %(item_width,'Cantaloupes',price_width,1.92))
print(format %(item_width,'Dried Apricots',price_width,8))
print(format %(item_width,'Prunes (4 lbs.)',price_width,12))
print('-'*int(width))
======================================== Item Price ---------------------------------------- Apples 0.40 Pears 0.50 Cantaloupes 1.92 Dried Apricots 8.00 Prunes (4 lbs.) 12.00 ----------------------------------------
'With a moo-moo here, and a moo-moo there'.find('moo')
7
title = "Monthy Python's Flying Circus"
title.find('Flying')
16
title.find('monty')
-1
seq = [1,2,3,4,5]
sep = '+'
sep.join(seq)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-55-31b72627b10d> in <module> 1 seq = [1,2,3,4,5] 2 sep = '+' ----> 3 sep.join(seq) TypeError: sequence item 0: expected str instance, int found
seq = ['1','2','3','4','5']
sep = '+'
sep.join(seq)
'1+2+3+4+5'
dirs = '','usr','bin','env'
dirs
('', 'usr', 'bin', 'env')
'/'.join(dirs)
'/usr/bin/env'
print('C:'+'\\'.join(dirs))
C:\usr\bin\env
'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'
if 'Gumby' in ['gumby','smith','jones']: print('Found it!')
name = 'Gumby'
names = ['gumby','smith','jones']
if name.lower() in names: print('Found it!')
Found it!
"model kantong magma gunung merapi".title()
'Model Kantong Magma Gunung Merapi'
Alternatifnya "capwords"
import string
string.capwords("model kantong magma gunung merapi")
'Model Kantong Magma Gunung Merapi'
'This is a test'.replace('is','eez')
'Theez eez a test'
'1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
'/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
' internal whitespace is kept '.strip()
'internal whitespace is kept'
names = ['gumby','smith','jones']
name = 'gumby '
if name in names: print("Found it!")
names = ['gumby','smith','jones']
name = 'gumby '
if name.strip() in names: print("Found it!")
Found it!
Dengan perintah print, kita dapat menampilkan banyak ekspresi, yaitu cukup dipisahkan dengan tanda koma, misalnya
print('Umur:', 42)
Umur: 42
nama = 'Anna'
panggilan = 'Mrs.'
sapaan = "Hallo, "
print(sapaan, panggilan, nama)
Hallo, Mrs. Anna
Import dapat mengambil sesuatu dan manamai dengan nama baru, misalnya
import somemodule
atau
from somemodule import somefunction
atau
from somemodule import somefunction, anotherfunction, yetanotherfunction
atau
from somemodule import *
import math as matematika
matematika.sqrt(16)
4.0
from math import sqrt as akar
akar(4)
2.0
oyot = akar
oyot(16)
4.0
Kita dapat menuliskan x = x + 1
dengan menuliskan tanda oprasi matematika sebelum tanda =
. Ini berlaku untuk operasi + - x /
dan %
x = 2
x += 1
x *=2
x
6
fnord = 'foo'
fnord += 'bar'
fnord *= 2
fnord
'foobarfoobar'
import this
nama = input('Sebutkan nama Anda: ')
if nama.endswith('Suryanto'):
print('Hallo Mr. Suryanto')
Hallo Mr. Suryanto
nama = input('Sebutkan nama Anda: ')
if nama.endswith('Suryanto'):
print('Hallo Mr. Suryanto')
else:
print('Hallo orang asing')
Hallo orang asing
num = input('masukkan sebuah angka: ')
if int(num) > 0:
print('angka positif')
elif int(num)<0 :
print('angka negatif')
else:
print('angka nol')
angka nol
# While Loops
x = 1
while x < 10:
print(x)
x +=1
1 2 3 4 5 6 7 8 9
# for Loops
words = ['this','is','an','ex','parrot']
for word in words:
print(word)
this is an ex parrot
numbers = [0,1,2,3,4,5,6,7,8,9,10]
for number in numbers:
print(number)
0 1 2 3 4 5 6 7 8 9 10
for number in range(1,10):
print(number)
1 2 3 4 5 6 7 8 9
range(10)
range(0, 10)
# Parallel iteration
nama = ['anne','beth','george','damon']
umur = [12,45,32,102]
for i in range(len(nama)):
print(nama[i], 'is', umur[i], ' tahun')
anne is 12 tahun beth is 45 tahun george is 32 tahun damon is 102 tahun
# Slighty loopy
[x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
[(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
def kuat(x):
'Menghitung kuadrat dari x'
return x*x
kuat.__doc__
'Menghitung kuadrat dari x'
kuat(3)
9
help(kuat)
Help on function kuat in module __main__: kuat(x) Menghitung kuadrat dari x