Strings in Python are sequence of character which is surrounded by either single quotation marks, or double quotation marks.
Strings Example:
"I'm going on a run"
"This is my 2nd opinion"
Multiline Strings:
We can assign a multiline string to a variable using three (""") quotes.
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
String Properties in Python:
Strings in Python are Immutable. It means that it can not be changed.
name = "Sameer"
name[0] = 'P' // This will throw an TypeError : 'str' object does not support item assignment.
how to validate the immutability of an object in python:
id() : we can get the memory address of an object using id(objectName). We can compare and conclude the immutability of string using this. As shown in below code block the memory address will be different for name variable before re-assignment and after re-assignment.
id(name) // This will give the memory address of name variable.
name = name.replace('S','D')
id(name)
Indexing in Python:
Indexing notation uses [] notation after the string(or variable assigned the string). It allows us to grab a single character from the string.
Character: h e l l o
Index: 0 1 2 3 4
Reverse Index: 0 -4 -3 -2 -1
Slicing in Python:
Slicing allow us to grab a subsection of mulitple characters, a "slice" of the string.
syntax:
[start:stop:step]
start: is a numercial index for the slice start
stop: is the index we will go up to (but not inlude).
step: is the size of the the "jump" we take.
String Concatination in Python:
'+' is use to concatinate the strings in python.
str1 = 'Hello'
str 2 = 'Sameer'
print(str1 + " " +str2)
String Multiplication in Python:
'*' is use to mulitply the strings in python.
str1 = 'H'
print(str1 * 10)
Print Formattng with Strings in Python:
Often we want to "inject" a variable into the string for printing. There are multiple ways to format strings for printing variables in them.
- .format() method.
'String here {} then also {}'.format('something1','something2')
print('The {2} {1} {0}'.format('fox', 'brown', 'quick'))
print('The {q} {b} {f}'.format(f='fox', b='brown', q='quick'))
- Float formatting follows "{value:width.precision f}".
result = 100/777 // output : 0.1287001287001287
print('The result is {r:2.3f}'.format(r=result)) //output: 0.129
- f-strings (formatted string literals).
name = 'Sameer'
print(f'Hello, his name is {name})
Escape Characters in Python :
To insert characters that are illegal in a string, we use an escape character. An escape character is a backslash "\" followed by the character we want to insert..
Code | Result |
---|---|
\' | Single Quote |
\" | double Quote |
\\ | Backslash |
\n | New line |
\t | Tab |
\b | Backspace |
Modify Strings in Python:
Python has a set of built-in methods that allows us to use on strings. However it wont change the origional string. If we want to change the origional string then we need to re-assign it. In this case the address of the variable will be changed which imply the immutable property of string. In below table optional parameter will be placed inside [].
Method | Description | Syntax |
---|---|---|
len() | returns the length of specified string. | len(string) |
upper() | returns the string in upper case. | string.upper() |
capitalize() | convert the first character to upper case. | string.capitalize() |
lower() | convert the string into lower case. | string.lower() |
swapcase() | Swaps cases, lower case becomes upper case and vice versa. | string.swapcase() |
title() | Converts the first character of each word to upper case. | string.title() |
center() | center align the string, using a specified character (space is default) as the fill character. | string.center(length, character) |
count() | Returns the number of times a specified value occurs in a string | string.count(value, [start], [end] |
encode() | encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used. | string.encode(encoding=encoding, [errors=errors]) |
endswith() | Returns true if the string ends with the specified value otherwise false. | string.endswith(value, [start], [end]) |
find() | Searches the string for a specified value and returns the first occurrence of the specified value if found otherwise returns -1. The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found. | string.find(value, [start], [end]) |
index() | Searches the string for a specified value and returns the first occurrence of the specified value if found otherwise raises an exception. | string.find(value, [start], [end]) |
isalnum() | it returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9). | string.isalnum() |
isalpha() | returns True if all the characters are alphabet letters (a-z). | string.isalpha() |
isdecimal() | returns True if all the characters are decimals (0-9). | string.isdecimal() |
isdigit() | returns True if all the characters are digits, otherwise False. Exponents, like ², are also considered to be a digit. | string.isdigit() |
isidentifier() | returns True if the string is a valid identifier, otherwise False. A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces. | string.isidentifier() |
islower() | returns True if all the characters are in lower case, otherwise False. Numbers, symbols and spaces are not checked, only alphabet characters. | string.islower() |
isnumeric() | The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the . are not. | string.isnumeric() |
isprintable() | returns True if all the characters are printable, otherwise False. Example of none printable character can be carriage return and line feed. | string.isprintable() |
isspace() | returns True if all the characters in a string are whitespaces, otherwise False. | string.isspace() |
istitle() | returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters, otherwise False. Symbols and numbers are ignored. | string.istitle() |
isupper() | returns True if all the characters are in upper case, otherwise False. | string.isupper() |
join() | The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator. | string.join(iterable) myDict = {"name":"Sam","coun.":"b"} mySep = "," x = mySep.join(myDict) print(x) => name,coun. |
lstrip() | Remove spaces to the left of the string: | string.lstrip(characters) |
strip() | removes any white-space from the begining or the end of string. | string.strip() |
maketrans() | returns a mapping table that can be used with the translate() method to replace specified characters. | string.maketrans(x, y, z) |
partition() | searches for a specified string, and splits the string into a tuple containing three elements. The first element contains the part before the specified string. The second element contains the specified string. The third element contains the part after the string. | string.partition(value) |
replace() | it replaces a string with another string. | string.replace(oldvalue, newvalue, count[optional]) |
rfind | Searches the string for a specified value and returns the last position. | string.rfind(value, start, end) |
rpartition() | Search for the last occurrence of a specified string, and return a tuple with three elements: | string.rpartition(value) |
rsplit() | splits a string into a list, starting from the right. If no "max" is specified, this method will return the same as the split() method. | string.rsplit(separator, [maxsplit]) |
split() | Split a string into a list where each word is a list item | string.split(separator, maxsplit) |
zfill() | adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done. | string.zfill(len) |