Strings

Strings

String dalam Python diapit oleh tanda kutip tunggal atau tanda kutip ganda.

'hello' sama dengan "hello".

Anda dapat menampilkan literal string dengan fungsi print():

Quotes Inside Quotes

Anda dapat menggunakan tanda kutip di dalam string, selama tanda kutip tersebut tidak cocok dengan tanda kutip yang ada di sekitar string tersebut:

print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

Menetapkan String ke Variabel

Menetapkan string ke variabel dilakukan dengan nama variabel diikuti tanda sama dengan dan string:

a = "Hello"
print(a)

String Multiline

Anda dapat menetapkan string multiline ke variabel dengan menggunakan tiga tanda kutip atau tiga tanda kutip tunggal:

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

b = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
# Catatan: dalam hasil, jeda baris disisipkan pada posisi yang sama seperti dalam kode.

print(a)

Strings are Arrays

Seperti banyak bahasa pemrograman populer lainnya, string dalam Python adalah array karakter Unicode.

Namun, Python tidak memiliki tipe data karakter; satu karakter hanyalah string dengan panjang 1.

Tanda kurung siku dapat digunakan untuk mengakses elemen string.

a = "Hello, World!"
print(a[1])

Perulangan Melalui String

Karena string adalah array, kita dapat melakukan perulangan melalui karakter-karakter dalam string dengan for loop.

for x in "banana":
  print(x)

String Length

Untuk mendapatkan panjang string, gunakan fungsi len()

a = "Hello, World!"
print(len(a))

Check String

Untuk memeriksa apakah frasa atau karakter tertentu ada dalam suatu string, kita dapat menggunakan kata kunci in.

txt = "The best things in life are free!"
print("free" in txt)

txt = "The best things in life are free!"
if "free" in txt:
  print("Yes, 'free' is present.")

Check if NOT

Untuk memeriksa apakah frasa atau karakter tertentu TIDAK ada dalam suatu string, kita dapat menggunakan kata kunci not in.

txt = "The best things in life are free!"
print("expensive" not in txt)

txt = "The best things in life are free!"
if "expensive" not in txt:
  print("No, 'expensive' is NOT present.")

Slicing Strings

Anda dapat mengembalikan rentang karakter menggunakan sintaksis irisan.

Tentukan indeks awal dan indeks akhir, dipisahkan dengan titik dua, untuk mengembalikan sebagian string.

# Dapatkan karakter dari posisi 2 ke posisi 5 (tidak termasuk):
b = "Hello, World!"
print(b[2:5])
# The first character has index 0.

Slice From the Start

Dengan menghilangkan indeks awal, rentang akan dimulai pada karakter pertama:

b = "Hello, World!"
print(b[:5])

Slice To the End

b = "Hello, World!"
print(b[2:])

Negative Indexing

Gunakan indeks negatif untuk memulai potongan dari akhir string:

b = "Hello, World!"
print(b[-5:-2])

# output : orl

Modify Strings

Python memiliki serangkaian metode bawaan yang dapat Anda gunakan pada string.

Upper Case

a = "Hello, World!"
print(a.upper())

Lower Case

a = "Hello, World!"
print(a.lower())

Remove Whitespace

Whitespace adalah spasi sebelum dan/atau sesudah teks sebenarnya, dan sering kali Anda ingin menghapus spasi ini.

a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

Replace String

Metode replace() mengganti string dengan string lain:

a = "Hello, World!"
print(a.replace("H", "J"))

Split String

Metode split() mengembalikan daftar di mana teks di antara pemisah yang ditentukan menjadi item daftar.

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

String Concatenation

Untuk menggabungkan, atau mengkombinasikan, dua string, Anda dapat menggunakan operator +.

a = "Hello"
b = "World"
c = a + b
d = a + " " + b
print(c)
print(d)

Format - Strings

Seperti yang kita pelajari di bab Variabel Python, kita tidak dapat menggabungkan string dan angka seperti ini:

age = 36
#This will produce an error:
txt = "My name is John, I am " + age
print(txt)

Tetapi kita dapat menggabungkan string dan angka dengan menggunakan f-string atau metode format()!

F-Strings

F-String diperkenalkan pada Python 3.6, dan sekarang menjadi cara yang lebih disukai untuk memformat string.

Untuk menetapkan string sebagai f-string, cukup letakkan f di depan literal string, dan tambahkan tanda kurung kurawal {} sebagai pengganti variabel dan operasi lainnya.

age = 36
txt = f"My name is John, I am {age}"
print(txt)

Placeholder dan Modifier

Placeholder dapat berisi variabel, operasi, fungsi, dan pengubah untuk memformat nilai.

price = 59
txt = f"The price is {price} dollars"
print(txt)

Placeholder dapat menyertakan pengubah untuk memformat nilai.

Pengubah disertakan dengan menambahkan titik dua : diikuti oleh tipe format yang sah, seperti .2f yang berarti angka titik tetap dengan 2 desimal:

price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)

Placeholder dapat berisi kode Python, seperti operasi matematika:

txt = f"The price is {20 * 59} dollars"
print(txt)

Escape Characters

Untuk menyisipkan karakter yang tidak sah dalam string, gunakan karakter escape.

Karakter escape adalah garis miring terbalik \ yang diikuti oleh karakter yang ingin Anda sisipkan.

Contoh karakter yang tidak sah adalah tanda kutip ganda di dalam string yang diapit oleh tanda kutip ganda:

# ini salah
txt = "We are the so-called "Vikings" from the north."

# tambahkan ``\"``
txt = "We are the so-called \"Vikings\" from the north."

Code

Result

'

Single Quote

\

Backslash

n

New Line

r

Carriage Return

t

Tab

b

Backspace

f

Form Feed

ooo

Octal value

xhh

Hex value

String Methods

Python memiliki serangkaian metode bawaan yang dapat Anda gunakan pada string.

Catatan

Semua metode string mengembalikan nilai baru. Metode ini tidak mengubah string asli.

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

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

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()

Joins the elements of an iterable to the end of the 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

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

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