String
String is a collection of items of same data type stored at contiguous memory locations.
(deja vu enough?) Well, string is array.
Python strings are "immutable" which means they cannot be changed after they are created.
Declare
To declare a string, you can assign variable to empty string
s = ''
You can use s = ''
to delete all characters of the string
Basics
Since, string is array, it has array's basic function.
Get array size
Use len(s)
s = 'Python'
len(s)
> s: 6
Check empty string
Check the len
.
s = 'Python'
if len(s) == 0:
print('Nothing is here!')
else:
print('String is not empty!')
Insert
Use slicing array. Common pattern is str[:pos] + something + str[pos:]
s = 'Python'
s2 = ' is great!'
s = s[:6] + s2 + s[6:]
> s: 'Python is great'
Delete
Same as insert, use slicing array to delete. Common pattern is str[:start] + str[end:]
s = 'Python is great'
s = s[:6] + s[14:]
> s: 'Python'
Find
Use find(string)
. You can user find(string, start, end)
to find in a specific range.
s = 'Python'
f = s.find('t')
nf = s.find('z')
r = s.find('t', 0, 1)
> f: 2
> nf: -1
> r: -1
Get sub-string
Use str[start:end]
'Python'[1:3]
> yt
Concat
Use +
operator.
'Python ' + 'is great' + '!'
> Python is great!
Validation of string
ASCII tables
Lookup for ASCII table here or simply here.
Check if character is a digit
You can use ord(char)
to get ASCII decimal number of a character.
Based on the ASCII table, you can see digits will have decimal number from 48
, which is 0 to 57
, which is 9.
if ord(str[0]) >= 48 and ord(str[0]) <= 57:
# it is a digit, do something
Remember number for ASCII '0' is 48.
There are digits from 0 to 9. So you can add more up to 9, which come up to 57.
You can use chr(number)
to convert ASCII code to a character.
zero = chr(48)
> 0
Built-in functions
Python has some built-in libraries to do fun thing on string. How to use them is alike. Below is some examples:
Python built-in functions can not only check a character but also a whole string.
isalpha
Use built-in function str.isalpha()
. It will return true
if string is alpha, false
if not alpha or empty.
str = 'Python is great!'
res = str[1].isalpha()
> res: true
isdigit
islower
isupper
Normalization
string to number
int(string)
: int to string.float(string)
: float to string.
number to string
str(value)
: number to string
case-sensitive
Use built-in functions:
char.lower()
: returns a string where all characters are lower case.char.upper()
: returns a string where all characters are upper case.
or you can change its ASCII number
s = "python"
c = chr(ord(s[2]) - 32)
> c: T
char_ascii + 32
: transform to lowercasechar_ascii - 32
: transform to uppercase
Input & output
In Python,
s = input() # then insert "Python is fun!"
> s: Python is fun!
To get each word, you can use string.split()
line = input().split() # insert "Python is fun!"
word = line[0]
> word: Python