8. PYTHON (Konsep Dasar) – Operasi String

Belajar Bahasa Python Lengkap

Seperti integer dan float, string di Python dapat ditambahkan atau digabungkan menggunakan proses yang disebut dengan concatenation. Baik menggunakan double quote atau single quote, proses ini tetap dapat dilakukan.

>>> "Belajar"+'Python'
'BelajarPython'
>>> print("Selamat Pagi"+","+"Sehat dan Sukses Selalu")
Selamat Pagi,Sehat dan Sukses Selalu

Integer yang berbentuk string juga dapat melakukan concatenation. Tetapi jika murni bertindak sebagai integer, maka akan menghasilkan error.

>>> '1'+'2'
'12'
>>> '1'+2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int

String dapat dikalikan dengan integer dan akan menghasilkan perulangan string sejumlah yang dikalikan. Tetapi string tidak dapat dikalikan dengan string atau float.

>>> print('python'*5)
pythonpythonpythonpythonpython
>>> 3*"yes"
'yesyesyes'
>>> '12'*'10'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
>>> 'python'*2.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'

LANJUTKAN BACA MATERI LENGKAP


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.