Tutorial Python untuk bukan pengatur cara/Dendam String: Perbezaan antara semakan

Kandungan dihapus Kandungan ditambah
Aurora (bincang | sumb.)
Algazel (bincang | sumb.)
kembang
Baris 1:
{{../Kandungan|Tambahan tentang List|IO Fail}}
Dan sekarang kita persembahkan muslihat licik yang boleh dilakukan dengan <code>string</code>:
<source lang="python">
Baris 39 ⟶ 40:
Ciri seterusnya menunjukkan sebahagian ciri khusus <code>string</code>:
<source lang="python">
def to_upperjadi_huruf_besar(stringrentetan):
## ConvertsMengubah arentetan ("string") tokepada upperhuruf casebesar
upper_casehuruf_besar = ""
for characteraksara in stringrentetan:
if 'a' <= characteraksara <= 'z':
locationlokasi = ord(characteraksara) - ord('a')
new_asciiascii_baru = locationlokasi + ord('A')
characteraksara = chr(new_asciiascii_baru)
upper_casehuruf_besar = upper_casehuruf_besar + characteraksara
return upper_casehuruf_besar
 
print jadi_huruf_besar("Ini adalah Teks")
 
print to_upper("This is Text")
</source>
 
dengan outputnya menjadi:
 
INI ADALAH TEKS
THIS IS TEXT
 
ThisIni worksbekerja becausekerana thekomputer computermewakilkan representsaksara-aksara thesesuatu charactersrentetan ofsebagai anombor string as numbers fromdari 0 toke 255. Python has amempunyai functionfungsi calleddigelar <code>ord()</code> (shortpendek foruntuk ''ordinal'') thatyang returnsmemulangkan asesuatu characteraksara assebagai a numbernombor. Juga Thereterdapat is also afungsi correspondingsepadan functionyang calleddipanggil <code>chr()</code> thatyang convertsmenukar asesebuah numbernombor intokepada a characteraksara. Dengan With this in mind theini, program shouldseharusnya startmenjadi tolebih be clearjelas. The first detailPerincian ispertama theadalah linebaris: <code>if 'a' <= characteraksara <= 'z':</code> whichyang checksmemeriksa tosama seeada ifsebuah ahuruf letteritu ishuruf lowerkecil caseatau tidak. Jika Ifya, itprogram isbergerak thenke thebaris next lines are usedberikutnya. Pertama, Firstia it is converted into adiubah locationmenjadi solokasi thatagar a&nbsp;=&nbsp;0, b&nbsp;=&nbsp;1, c&nbsp;=&nbsp;2 anddan soseterusnya ondengan with the linebaris: <code>locationlokasi = ord(characteraksara) - ord('a')</code>. Kemudian, Nextnilai thebaharu newditemui value is found withdengan <code>new_asciiascii_baru = locationlokasi + ord('A')</code>. ThisNilai valueini isditukar converted back to akembali charactermenjadi thataksar isyang nowberbentuk upperhuruf casebesar.
 
Sekarang kita berlatih menaip secara interaktif:
Now for some interactive typing exercise:
 
>>> '''# Integer toke StringRentetan'''
>>> '''2'''
2
Baris 72 ⟶ 74:
>>> '''`123`'''
'123'
>>> '''# StringRentetan toke Integer'''
>>> '''"23"'''
'23'
Baris 81 ⟶ 83:
>>> '''int("23") * 2'''
46
>>> '''# FloatNombor toapung Stringke Rentetan'''
>>> '''1.23'''
1.23
>>> '''repr(1.23)'''
'1.23'
>>> '''# FloatNombor toapung ke Integer'''
>>> '''1.23'''
1.23
Baris 93 ⟶ 95:
>>> '''int(-1.23)'''
-1
>>> '''# StringRentetan toke FloatNombor apung'''
>>> '''float("1.23")'''
1.23
Baris 103 ⟶ 105:
'1.23'
 
IfJika youanda haven'tbelum guessedmengagaknya already thelagi, functionfungsi <code>repr()</code> canboleh convert amengubah integer to a stringkepada andrentetan thedan functionfungsi <code>int()</code> canmelakukan convertoperasi a string to an integersebaliknya. The functionFungsi <code>float()</code> canboleh convertmengubah arentetan stringkepada to''floating apoint floatnumber'' atau nombor titik apung. TheFungsi <code>repr()</code> functionmemulangkan returnswakil asesuatu printableyang representationdapat of somethingdicetak. Kod <code>`...`</code> convertsjuga almost everythingmengubah intohampir asemua string,kepada toorentetan. Here are some examplesBerikut ofbeberapa thiscontoh:
 
>>> '''repr(1)'''
Baris 114 ⟶ 116:
'[4, 42, 10]'
 
TheFungsi <code>int()</code> functioncuba triesmengubah to convert a stringrentetan (oratau anombor floatapung) into akepada integer. ThereJuga isterdapat alsofungsi ayang similarsama functionyang calleddipanggil <code>float()</code> thatyang willakan convert amengubah integer oratau arentetan stringkepada intonombor aapung. float. Satu Anotherlagi functionfungsi thatyang Pythondimiliki hasPython isadalah thefungsi <code>eval()</code> function. TheFungsi <code>eval()</code> functionmengambil takesrentetan adan string and returnsmemulangkan data ofjenis theyang typedifikirkan thatPython pythontelah thinks it foundditemuinya. For exampleContoh:
 
>>> '''v = eval('123')'''
Baris 126 ⟶ 128:
[1, 2, 3] <type 'list'>
 
IfJika youanda usemengguna thefungsi <code>eval()</code> functionanda youharus shouldpastikan checkyang thatia itmemulangkan returnsjenis theyang typeanda that you expectsangka.
 
OneSatu usefulfungsi stringrentetan functionatau is<code>string</code> theadalah kaedah <code>split()</code> method(pisah). Here's anIni examplecontoh:
 
>>> '''"ThisIni isadalah abeberapa bunch of wordsperkataan".split()'''
['ThisIni', 'isadalah', 'abeberapa', 'bunch', 'of', 'wordsperkataan']
>>> '''text = "FirstKelompok batchpertama, secondkelompok batchkedua, thirdketiga, fourthkeempat"'''
>>> '''text.split(",")'''
['FirstKelompok batchpertama', ' secondkelompok batchkedua', ' thirdketiga', ' fourthkeempat']
 
Perhatikan bagaimana <code>split()</code> mengubah rentetan menjadi satu senarai rentetan. Rentetan dipisah dengan ruang putih secara lalai atau dengan argumen pilihan (dalam kes ini, tanda koma). Anda juga boleh menambah argumen yang memberitahu <code>split()</code> berapa kali pemisah akan digunakan bagi memisah teks. Contoh:
Notice how <code>split()</code> converts a string into a list of strings. The string is split by whitespace by default or by the optional argument (in this case a comma).
You can also add another argument that tells <code>split()</code> how many times the separator will be used to split the text. For example:
 
>>> '''list = text.split(",")'''
Baris 143 ⟶ 144:
4
>>> '''list[-1]'''
' fourthkeempat'
>>> '''list = text.split(",", 2)'''
>>> '''len(list)'''
3
>>> '''list[-1]'''
' thirdketiga, fourthkeempat'
 
<!-- TODO add more on strings -->
=== Slicing strings (and lists) ===
 
=== Menghiris rentetan (dan senarai) ===
Strings can be cut into pieces &mdash; in the same way as it was shown for lists in the previous chapter &mdash; by using the ''slicing'' "operator" <tt>[:]</tt>. The slicing operator works in the same way as before: text[first_index:last_index] (in very rare cases there can be another colon and a third argument, as in the example shown below).
 
Rentetan dapat dihiris &mdash; dengan cara yang sama yang ditunjukan dengan senarai dalam bab sebelum ini &mdash; dengan menggunakan "operator" ''penghiris'' <code>[:]</code>. Operator penghiris bekerja dengan cara yang sama seperti dahulu: teks[indeks_pertama:indeks_terakhir] (dalam kes-kes yang jarang diketemu, sebuah tanda titik berganda dan argumen ketiga boleh digunakan, seperti dipaparkan dalam contoh berikut).
 
Agar kita tidak terkeliru dengan angka indeks, paling mudah jika kita melihatnya sebagai ''tempat ketip'', di mana kita dapat menghiris rentetan kepada bahagian-bahagiannya. Ini satu contoh yang menunjukkan tempat ketip (kuning) dan nombor-nombor indeks (merah dan biru) buat rentetan teks:
In order not to get confused by the index numbers, it is easiest to see them as ''clipping places'', possibilities to cut a string into parts. Here is an example, which shows the clipping places (in yellow) and their index numbers (red and blue) for a simple text string:
 
<tt>