STRINGS
String Literals: A string is a group of characters. String literals in python are surrounded by either single quotation marks, and double quotation marks or triple quotes.
'hello' is the same as "hello“ and “””hello”””
Assign String to a Variable: Assigning a string to a variable is done with the variable name followed by an equal sign and the string.
Example
a = "Hello"�print(a)
Multiline Strings: You can assign a multiline string to a variable by using three quotes.
Example
a = ""“This is python programming and
very popular language in now a days."""�print(a)
Or
a =‘’’This is python programming and
very popular language in now a days.’’’�print(a)
Accessing Values in Strings:
Example:
var1="hello“
var2="how are you“
print("var1 is",var1)
print("var2 is",var2)
Output:
var1 is hello
var2 is how are you
Updating Strings:
You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether.
Example:
var1='Hello World!'
print("Updated String :- ", var1[:6] + 'Python')
print(var1)
Output:
Updated String :- Hello Python
Hello World!
Slicing: You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.
Example-1:
#Get the characters from position 2 to position 5 (not included):
b = "Hello, World!“
print(b[2:5])
Output:
llo
Example-2:
#print the string in reverse order
print(a[::-1])
Output:
olleh
Escape Characters:
Example: You will get an error if you use double quotes inside a string that is surrounded by double quotes:
txt = "We are the so-called "Vikings" from the north."
If you execute the above code it shows error, because you placed “Vikings” in txt illegally.To fix this problem, use the escape character \":
Example
The escape character allows you to use double quotes when you normally would not be allowed:
txt = "We are the so-called \"Vikings\" from the north."
Code | Result |
\' | Single Quote |
\\ | Backslash |
\n | New Line |
\r | Carriage Return |
\t | Tab |
\b | Backspace |
\ooo | Octal value |
\xhh | Hex value |
Other escape characters used in Python:
Example:
print("Single Quote escape character: ","Hello\'world\'")
print("Double Quote escape character: ","Hello\"world\"")
print("Back Slash escape character: ","Hello\\world")
print("New Line escape character: ","Hello\nworld")
print("Carriage Return escape character: ","Hello\rWorld")
print("Tab escape character: ","Hello\tworld")
print("Back Space escape character: ","Hello\bworld")
print("Octal escape character: ","\110\145\154\154\157")
print("Hexa-decimal escape character: ","\x48\x65\x6c\x6c\x6f")
Output:
Single Quote escape character: Hello'world'
Double Quote escape character: Hello"world"
Back Slash escape character: Hello\world
New Line escape character: Hello world
Worldage Return escape character: Hello
Tab escape character: Hello world
Back Space escape character: Hellworld
Octal escape character: Hello
Hexa-decimal escape character: Hello
String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
Example:
a="Hello"
b="Python"
print(a+b) #Concatenation of a and b
print(a*3) #displays a 3 times
print(a[2]) #displays the 2 index element in a
print(a[1:4]) #displays the characters from 1 to 4 except 4th index
print('H'in a)
print('H'not in a)
Output:
HelloPython
HelloHelloHello
l
ell
True
False
Example:
s=print(“Hello\tfrom\nlbrce”)
print(s)
Output:
Hello from
lbrce
Example:
s=print(r“Hello\tfrom\nlbrce”)
print(s)
Output:
Hello\tfrom\nlbrce
Example:
s=“Hello Every\xone”
print(s)
Output:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 11-12: truncated \xXX escape
Example:
s=r“Hello Every\xone”
print(s)
Output:
'Hello Every\\xone'
Unicode Strings:
Method | Description |
capitalize() | Converts the first character to upper case |
casefold() | Converts string into lower case |
center() | Returns a cantered string |
count() | Returns the number of times a specified value occurs in a string |
encode() | Returns an encoded version of the string |
endswith() | Returns true if the string ends with the specified value |
expandtabs() | Sets the tab size of the string |
find() | Searches the string for a specified value and returns the position of where it was found |
format() | Formats specified values in a string |
format_map() | Formats specified values in a string |
Searches the string for a specified value and returns the position of where it was found | |
Returns True if all characters in the string are alphanumeric | |
Returns True if all characters in the string are in the alphabet | |
Returns True if all characters in the string are decimals | |
Returns True if all characters in the string are digits | |
Returns True if the string is an identifier | |
Returns True if all characters in the string are lower case | |
Returns True if all characters in the string are numeric | |
Returns True if all characters in the string are printable | |
Returns True if all characters in the string are whitespaces | |
Returns True if the string follows the rules of a title | |
Returns True if all characters in the string are upper case |
Joins the elements of an iterable to the end of the string | |
Returns a left justified version of the string | |
Converts a string into lower case | |
Returns a left trim version of the string | |
Returns a translation table to be used in translations | |
Returns a tuple where the string is parted into three parts | |
Returns a string where a specified value is replaced with a specified value | |
Searches the string for a specified value and returns the last position of where it was found | |
Searches the string for a specified value and returns the last position of where it was found | |
Returns a right justified version of the string | |
Returns a tuple where the string is parted into three parts | |
Splits the string at the specified separator, and returns a list | |
Returns a right trim version of the string |
Splits the string at the specified separator, and returns a list | |
Splits the string at line breaks and returns a list | |
Returns true if the string starts with the specified value | |
Returns a trimmed version of the string | |
Swaps cases, lower case becomes upper case and vice versa | |
Converts the first character of each word to upper case | |
Returns a translated string | |
Converts a string into upper case | |
Fills the string with a specified number of 0 values at the beginning |
1.capitalize(): The capitalize() method returns a string where the first character is upper case.
Syntax: string_variable.capitalize()
Parameters: No Parameters
Example:
s=“python programming”
s.capitalize()
Output: Python programming
2.casefold(): The casefold() method returns a string where all the characters are lower case. This method is similar to the lower() method, but the casefold() method is stronger, more aggressive, meaning that it will convert more characters into lower case, and will find more matches when comparing two strings and both are converted using the casefold() method.
Syntax: string_variable.casefold()
Parameters: No Parameters
Example:
s=“PYTHON PROGRAMMING”
s.casefold()
Output: python programming
3. center(): The center() method will center align the string, using a specified character (space is default) as the fill character.
Syntax: string.center(length, character)
Parameter Values:
�
Parameter | Description |
length | Required. The length of the returned string |
character | Optional. The character to fill the missing space on each side. Default is " " (space) |
Example:
txt = "banana"
x = txt.center(20, "O")
print(x)
Output: OOOOOOObananaOOOOOOO
4. count(): The count() method returns the number of times a specified value appears in the string.
Syntax: string.count(value, start, end)
Parameters:
Parameter | Description |
value | Required. A String. The string to value to search for |
start | Optional. An Integer. The position to start the search. Default is 0 |
end | Optional. An Integer. The position to end the search. Default is the end of the string |
Example:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x)
Output: 2
5. encode(): The encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.
Syntax: string.encode(encoding=encoding, errors=errors)
Parameters:
Parameter | Description |
encoding | Optional. A String specifying the encoding to use. Default is UTF-8 |
errors | Optional. A String specifying the error method. Legal values are:� |
'backslashreplace' | - uses a backslash instead of the character that could not be encoded |
'ignore' | - ignores the characters that cannot be encoded |
'namereplace' | - replaces the character with a text explaining the character |
'strict' | - Default, raises an error on failure |
'replace' | - replaces the character with a questionmark |
'xmlcharrefreplace' | - replaces the character with an xml character |
Example:
txt = "My name is Ståle"
print(txt.encode(encoding="ascii",errors="backslashreplace"))
print(txt.encode(encoding="ascii",errors="ignore"))
print(txt.encode(encoding="ascii",errors="namereplace"))
print(txt.encode(encoding="ascii",errors="replace"))
print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))
Output:
b'My name is St\\xe5le'�b'My name is Stle'�b'My name is St\\N{LATIN SMALL LETTER A WITH RING ABOVE}le'�b'My name is St?le'�b'My name is Ståle'
6. endswith(): The endswith() method returns True if the string ends with the specified value, otherwise False.
Syntax: string.endswith(value, start, end)
Parameter | Description |
value | Required. The value to check if the string ends with |
start | Optional. An Integer specifying at which position to start the search |
end | Optional. An Integer specifying at which position to end the search |
Parameter Values
Example:
txt = "Hello, welcome to my world."
x = txt.endswith("my world.")
print(x)
Output: True
7. expandtabs(): The expandtabs() method sets the tab size to the specified number of whitespaces.
Syntax: string.expandtabs(tabsize)
Parameter: tabsize (optional). A number specifying the tabsize. Default tabsize is 8
Example:
txt = "H\t\te\tl\tl\to"
print(txt)
print(txt.expandtabs())
print(txt.expandtabs(2))
print(txt.expandtabs(4))
print(txt.expandtabs(10))
Output:
H e l l o
H e l l o
H e l l o
H e l l o
H e l l o
H e l l o H e l l o H e l l o H e l l o H e l l o
8. find():
Syntax: string.find(value, start, end)
Parameters:
Parameter | Description |
value | Required. The value to search for |
start | Optional. Where to start the search. Default is 0 |
end | Optional. Where to end the search. Default is to the end of the string |
9. index:
The index() method finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found.
The index() method is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found.
Syntax: string.find(value, start, end)
Parameters:
Parameter | Description |
value | Required. The value to search for |
start | Optional. Where to start the search. Default is 0 |
end | Optional. Where to end the search. Default is to the end of the string |
Example-1:
txt = "Hello, welcome to my world."
x = txt.find("e")
print(x)
Output: 1
Example-2:
txt = "Hello, welcome to my world."
x = txt.find(“a")
print(x)
Output: -1
10. isalnum(): The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
Syntax: string.isalnum()
Parameters: No-parameters
Example:
txt = "Company 12"
x = txt.isalnum()
print(x)
Output: False
11. isalpha(): The isalpha() method returns True if all the characters are alphabet letters (a-z).
Syntax: string.isalpha()
Parameters: No-parameters
Example:
txt = "Company 12"
x = txt.isalpha()
print(x)
Output: False
12. isdecimal(): The isdecimal() method returns True if all the characters are decimals (0-9).
Syntax: string.isdecimal()
Parameters: No-parameters
Example:
a = "\u0030" #unicode for 0
b = "\u0047" #unicode for G
print(a.isdecimal())
print(b.isdecimal())
Output: True, False
13. isdigit(): The isdigit() method returns True if all the characters are digits, otherwise False.
Syntax: string.isdigit()
Parameters: No-parameters
Example:
txt = "50800“
x = txt.isdigit()
print(x)
Output:
True
14. isidentifier(): The isidentifier() method 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
Syntax: string.isidentifier()
Parameters: No-parameters
Example:
a = "MyFolder"
b = "Demo002"
c = "2bring"
d = "my demo"
print(a.isidentifier())
print(b.isidentifier())
print(c.isidentifier())
print(d.isidentifier())
Output:
True�True�False�False
.
15. islower()/isupper: The islower() method returns True if all the characters are in lower case, otherwise False. Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax: string.islower()
Parameters: No-parameters
Example:
a = "Hello world!"
b = "hello 123"
print(a.islower())
print(b.islower())
Output: False, True
16. isprintable(): The isprintable() method returns True if all the characters are printable, otherwise False. Example of none printable character can be carriage return and line feed.
Syntax: string.isprintable()
Parameters: No-parameters
Example:
txt = "Hello!\nAre you #1?"
x = txt.isprintable()
print(x)
Output:
False
17. isspace(): The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
Syntax: string.isspace()
Parameters: No-parameters
Example:
a = “ kl !"
print(a.isspace())
Output: False
18. istitle(): The istitle() method 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.
Syntax: string.istitle()
Parameters: No-parameters
Example: a = "HELLO, AND WELCOME TO MY WORLD"
b = "Hello"
c = "This Is %'!?"
print(a.istitle())
print(b.istitle())
print(c.istitle())
19. isspace(): The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
Syntax: string.isspace()
Parameters: No-parameters
Example:
a = “ kl !"
print(a.isspace())
Output: False
20. join(): The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.
Syntax: string.join(iterable)
Parameters: iterable-Required Any iterable object where all the returned values are strings
Example:
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)
Output:
John#Peter#Vicky
TUPLES
sets
SETS in Python
DICTIONARIES