String is a collection of alphabets, words or other characters. String represent in double quote " "
or single quote ' '
Example:
- firstName = "Rady"
- lastName = "Y"
- schoolName = 'PNC'
- studentName = 'Bopha'
- text = "Hello world in 1995"
Convert integer, float and boolean to string
- floatNumber = 10.5 ➡️ string = str(floatNumber)
// "10.5"
- number = 10 ➡️ string = str(number)
// "10"
- isBoolean = True ➡️ string = string(isBoolean)
// "True"
- isBoolean = False ➡️ string = string(isBoolean)
// "False"
- string = input()
- string = str(input())
- number = int(input())
- number = float(input())
- print("Hello world")
- print(100)
- print(10.5)
- print(True)
- number = 10 ➡️ print(number)
- string = 'rady' ➡️ print(string)
- number = 10.5 ➡️ print(number)
- hasNumber = False ➡️ print(hasNumber)
To access a string we use []
sign and index
of each character starting from 0
- text = "ABC" ➡️ text[0]
// A
- text = "ABC" ➡️ text[1]
// B
- text = "ABC" ➡️ text[2]
// C
- text = "ABC" ➡️ text[3]
// IndexError: string index out of range
- string = "abc" ➡️ len(string)
// 3
- string = "abc" ➡️ string.upper()
// ABC
- string = "aBc" ➡️ string.lower()
// abc
- string = "abc" ➡️ string.isupper()
// False
- string = "abc" ➡️ string.isLower()
// True
- string = "abc" ➡️ string.isnumeric()
// False
- string = "12" ➡️ string.isnumeric()
// True
- number = 12 ➡️ str(number)
// "12"
- string = "A" + "B"
// AB
- string = "5" + "6"
// 56
- string = 10 + "7"
// TypeError: unsupported operand type(s) for +: 'int' and 'str'
- string = 5.6 + "A"
// TypeError: unsupported operand type(s) for +: 'float' and 'str'
- string = str(100) + "8"
// 1008
For loop iteration by default incrementing from 0
it th same index of string
# Python
text = "abc"
for i in range(len(text)):
print(text[i])
# Output of code above:
a
b
c
# Python
text = "abc"
i = 0
while i < len(text):
print(text[i])
i = i + 1
# Output of code above:
a
b
c