String Flashcards
Length of string
len(“ola”)
Concat string
i = ‘abra’
b = ‘cadabra’
print(a+b)
-> abracadabra
print(1 + ‘abra’)
TypeError: can only concatenate str (not “int”) to str
Char by index
name = ‘Nonna’
name[1]
will return 0
Get substring from a string
fullName = ‘Nonna Dzhabieva’
fistname = fullName[0:5]
firstname -> ‘Nonna’
you can slice from the end using negative index . Note we slice from -10 to -1 not to -1 to -10
lastName = fullName[-10:-1]
we can slice from beginning to a specific char by omitting first index
firstName = fullName[:5]
or from specific char to the very end of string
lastName = fullName[7:]
Immutable?
Cannot be changes after its created
To alter a string you have to create a new one
lower and uper
fullName = ‘Nonna Dzhabieva’
t = fullName.lower()
‘nonna dzhabieva’
k = fullName.upper()
‘NONNA DZHABIEVA’
Removing whitespaces
name = ‘ Nonna ‘
a = name.strip()
‘Nonna’
l = name.lstrinp(). - removes from left only
‘Nonna ‘
r = name.rstrip() - removes from left
‘ Nonna’
Starts and ends
name = ‘Nonna’
name.startswith(‘No’)
true
name.startswith(‘no’) - case sensetive
false
name.endswith(‘nna’)
true
Title and capitalize
str.capitalize(): Capitalizes the first character of the string.
str.title(): Converts the first character of each word to uppercase.
Find and index
str.find() / str.index(): Searches the string for a specified value and returns its position.
name = “Alan Dzhabiev”
alan.find(‘lan’)
1
alan.index(‘l’)
1
both are the same but index raises ValueError if substring is not found
Replace
str.replace(): Replaces a specified phrase with another specified phrase.
name = ‘Nonna Kurbanova’
name.replace(‘Kurbanova’, ‘Dzhabieva’)
‘Nonna Dzhabieva’
Split and join
str.split(): Splits the string into a list based on a separator. separator can be any char or white space
name = “Alan Dzhabiev”
name.split(‘ ‘)
[‘Alan’, ‘Dzhabiev’]
str.join(): Joins elements of an iterable (like a list) into a single string.
words = [‘Hello’, ‘world’, ‘Python’, ‘is’, ‘awesome’]
sentence = ‘ ‘.join(words)
Output: “Hello world Python is awesome”
Reading from console
input(“Whats your name?”)
Whats your name?Nonna
‘Nonna’
or you can just call
name = input()
without any prompt
Multiplying string
name = ‘Nonna’
name * 5
‘NonnaNonnaNonnaNonnaNonna’
you can multiply string by number
but cant do string * string
“Nonna” * “Nonna” -> error
Data casting
int(‘9’)
9
float(‘8.9’)
8.9
str(7)
‘7’
bool(1)
True
bool(6)
True
bool(-1)
True
bool(0)
false