Strings
It is an instance of str class. It is a sequence of characters. It is immutable object.
assignment
use single or double quotes to assign string. multiline strings usually tripple double quotes.
python
name = 'Kibria'
message = """
This is a line one.
This is line 2.
This is last line.
"""
# True multiline, line break kept
multi_line = 'This is a string' \
'This is another string' \
'This is yet another string'
# it looks like multiline but it is not.
# It only one string. It is for better readability.get the length
built-in functions len() to get the length of string
python
name = 'Kibria'
print(len(name))
# 6methods
There are many str methods
upper()to convert string to uppercaselower()to convert string to lowercasecapitalize()to convert first character to uppercasetitle()to convert first character of each word to uppercasecount()to count the number of times a substring occurs in a stringfind()to find the index of a substring in a stringreplace()to replace a substring in a string with another substringsplit()to split a string into a list of substringsstrip()to remove whitespace from both sides of a stringrstrip()to remove whitespace from right side of a stringlstrip()to remove whitespace from left side of a stringisalnum()to check if all characters in a string are alphanumericisalpha()to check if all characters in a string are alphabeticisdigit()to check if all characters in a string are digitsislower()to check if all characters in a string are lowercaseisupper()to check if all characters in a string are uppercaseisspace()to check if all characters in a string are whitespaces
python
name = 'Kibria'
# name has all the methods of str class
name_upper = name.upper()
print(name_upper)
# KIBRIA
# does it modified the name?
print(name)
# Kibria
# No, because it is immutable hence it created new objecthow to concatenation strings?
Use + operator.
You have to use type conversion explicitly.
python
name = 'Kibria'
age = 41
gretting = 'Hi, ' + name + '. You are ' + str(age) + ' years old.'
print(gretting)
# Hi, Kibria. You are 41 years old.You can use f-string f"".
Use expresion inside {}. It also try to convert other types to strings automatically. It is most popular.
python
name = 'Kibria'
age = 41
gretting = f'Hi, {name}. You are {age} years old.'
print(gretting)
# Hi, Kibria. You are 41 years old.You can use format methods of str class.
python
name = 'Kibria'
age = 41
gretting = 'Hi, {}. You are {} years old.'.format(name, age)
print(gretting)
# Hi, Kibria. You are 41 years old.You can also do old fashion way, string interpolation.
python
name = 'Kibria'
age = 41
gretting = 'Hi, %s. You are %d years old.' % (name, age)
print(gretting)
# Hi, Kibria. You are 41 years old.