String
String
In [ ]: print("Hello")
print('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
In [1]:
a = "Hello"
print(a)
Hello
Multiline Strings You can assign a multiline string to a variable by using three quotes:
Example
In [3]:
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Strings are Arrays Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Example Get the character at position 1 (remember that the first character has the position 0):
In [4]:
a = "Hello, World!"
print(a[1])
Looping Through a String Since strings are arrays, we can loop through the characters in a string, with a for loop.
In [5]:
for x in "banana":
print(x)
b
a
n
a
n
a
String Length To get the length of a string, use the len() function.
In [6]:
a = "Hello, World!"
print(len(a))
13
Check String To check if a certain phrase or character is present in a string, we can use the keyword in.
True
Use it in an if statement:
In [8]:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Check if NOT To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
In [9]:
txt = "The best things in life are free!"
print("expensive" not in txt)
True
Use it in an if statement:
In [10]:
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
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.
llo
Slice From the Start By leaving out the start index, the range will start at the first character:
Example Get the characters from the start to position 5 (not included):
In [12]:
b = "Hello, World!"
print(b[:5])
Hello
Slice To the End By leaving out the end index, the range will go to the end:
Example Get the characters from position 2, and all the way to the end:
In [13]:
b = "Hello, World!"
print(b[2:])
llo, World!
Negative Indexing Use negative indexes to start the slice from the end of the string: Example Get the characters:
In [14]:
b = "Hello, World!"
print(b[-5:-2])
orl
Upper Case Example The upper() method returns the string in upper case:
In [15]:
a = "Hello, World!"
print(a.upper())
HELLO, WORLD!
Lower Case Example The lower() method returns the string in lower case:
In [16]:
a = "Hello, World!"
print(a.lower())
hello, world!
Remove Whitespace Whitespace is the space before and/or after the actual text, and very often you want to remove this space.
Example The strip() method removes any whitespace from the beginning or the end:
In [17]:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Hello, World!
Replace String Example The replace() method replaces a string with another string:
In [18]:
a = "Hello, World!"
print(a.replace("H", "J"))
Jello, World!
Split String The split() method returns a list where the text between the specified separator becomes the list items.
Example The split() method splits the string into substrings if it finds instances of the separator:
In [19]:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
The capitalize() method returns a string where the first character is upper case, and the rest is lower case.
In [20]:
txt = "hello, and welcome to my world."
x = txt.capitalize()
print (x)
In [21]:
txt = "python is FUN!"
x = txt.capitalize()
print (x)
Python is fun!
In [22]:
txt = "36 is MY age."
x = txt.capitalize()
print (x)
36 is my age.
The casefold() method returns a string where all the characters are lower case.
x = txt.casefold()
print(x)
The center() method will center align the string, using a specified character (space is default) as the fill character.
length Required: The length of the returned string character Optional: The character to fill the missing space on each side. Default is " " (space)
Example Print the word "banana", taking up the space of 20 characters, with "banana" in the middle:
In [24]:
txt = "banana"
x = txt.center(20)
print(x)
banana
x = txt.center(20, "O")
print(x)
OOOOOOObananaOOOOOOO
The count() method returns the number of times a specified value appears in the string.
Parameter Values 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 Return the number of times the value "apple" appears in the string:
x = txt.count("apple")
print(x)
In [29]:
txt = "I love apples, apple are my favorite fruit"
print(x)
The endswith() method returns True if the string ends with the specified value, otherwise False.
Parameter Values Parameter Description value Required: The value to check if the string ends with. This value parameter can also be a tuple, then the
method returns true if the string ends with any of the tuple values. start Optional: An Integer specifying at which position to start the search end
Optional: An Integer specifying at which position to end the search
In [30]:
txt = "Hello, welcome to my world."
x = txt.endswith(".")
print(x)
True
The find() method finds the first occurrence of the specified value.
Parameter Values 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
In [31]:
txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)
Example Where in the text is the first occurrence of the letter "e" when you only search between position 5 and 10?:
In [32]:
txt = "Hello, welcome to my world."
x = txt.find("e", 5, 10)
print(x)
Example If the value is not found, the find() method returns -1, but the index() method will raise an exception:
print(txt.find("q"))
print(txt.index("q"))
-1
The format() method formats the specified value(s) and insert them inside the string's placeholder.
Parameter Values
value1, value2... Required: One or more values that should be formatted and inserted in the string.
The values are either a list of values separated by commas, a key=value list, or a combination of both.
Example Insert the price inside the placeholder, the price should be in fixed point, two-decimal format:
In [34]:
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
The Placeholders The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even empty placeholders {}.
In [36]: txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)
print(txt1)
print(txt2)
print(txt3)
My name is John, I'm 36
My name is John, I'm 36
My name is John, I'm 36
Formatting Types
Inside the placeholders you can add a formatting type to format the result:
#To demonstrate, we insert the number 8 to set the available space for the value to 8 characters.
In [37]:
txt = "We have {:<8} chickens."
print(txt.format(49))
We have 49 chickens.
#To demonstrate, we insert the number 8 to set the available space for the value to 8 characters.
In [38]:
txt = "We have {:>8} chickens."
print(txt.format(49))
We have 49 chickens.
In [39]:
txt = "We have {:^8} chickens."
print(txt.format(49))
We have 49 chickens.
In [40]:
txt = "The temperature is {:=8} degrees celsius."
print(txt.format(-5))
In [43]:
txt = "The temperature is between {:+} and {:+} degrees celsius."
print(txt.format(-3, 7))
In [44]:
txt = "The temperature is between {:-} and {:-} degrees celsius."
print(txt.format(-3, 7))
In [45]:
txt = "The temperature is between {:-} and {:-} degrees celsius."
print(txt.format(-3, 7))
: :Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers)
print(txt.format(-3, 7))
print(txt.format(13800000000))
print(txt.format(13800000000))
:b Binary format
In [49]:
txt = "The binary version of {0} is {0:b}"
print(txt.format(5))
:d Decimal format
We have 5 chickens.
#Use "f" to convert a number into a fixed point number, default with 6 decimals, but use a period followed by a number to specify the number of
decimals:
#without the ".2" inside the placeholder, this number will be displayed like this:
:o Octal format
print(txt.format(10))
:% Percentage format
In [54]:
txt = "You scored {:%}"
print(txt.format(0.25))
In [55]:
txt = "You scored {:.0%}"
print(txt.format(0.25))
index() Searches the string for a specified value and returns the position of where it was found
The index() method finds the first occurrence of the specified value.
In [56]:
txt = "Hello, welcome to my world."
x = txt.index("welcome")
print(x)
Example Where in the text is the first occurrence of the letter "e" when you only search between position 5 and 10?:
In [57]:
txt = "Hello, welcome to my world."
x = txt.index("e", 5, 10)
print(x)
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.
print(txt.find("q"))
print(txt.index("q"))
-1
The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
Syntax string.isalnum()
In [59]:
txt = "Company12"
x = txt.isalnum()
print(x)
True
x = txt.isalnum()
print(x)
False
The isalpha() method returns True if all the characters are alphabet letters (a-z).
Syntax string.isalpha()
x = txt.isalpha()
print(x)
True
In [62]:
txt = "Company10"
x = txt.isalpha()
print(x)
False
The isascii() method returns True if all the characters are ascii characters (a-z).
In [63]:
txt = "Company123"
x = txt.isascii()
print(x)
True
The isdecimal() method returns True if all the characters are decimals (0-9).
In [64]:
txt = "1234"
x = txt.isdecimal()
print(x)
True
The isdigit() method returns True if all the characters are digits, otherwise False.
Syntax string.isdigit()
In [67]:
txt = "581926"
x = txt.isdigit()
print(x)
True
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()
In [69]:
a = "MyFolder"
b = "Demo002"
c = "2bring"
d = "my demo"
print(a.isidentifier())
print(b.isidentifier())
print(c.isidentifier())
print(d.isidentifier())
True
True
False
False
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()
In [1]:
txt = "hello world!"
x = txt.islower()
print(x)
True
In [2]:
a = "Hello world!"
b = "hello 123"
c = "mynameisPeter"
print(a.islower())
print(b.islower())
print(c.islower())
False
True
False
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.
"-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.
Syntax string.isnumeric()
In [4]:
a = "565543"
b = "-1"
c = "1.5"
x = a.isnumeric()
y = b.isnumeric()
z = c.isnumeric()
print(x)
print(y)
print(z)
True
False
False
The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
Syntax string.isspace()
In [5]:
txt = " "
x = txt.isspace()
print(x)
True
In [6]:
txt = " s "
x = txt.isspace()
print(x)
False
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.
Syntax string.istitle()
x = txt.istitle()
print(x)
True
print(a.istitle())
print(b.istitle())
print(c.istitle())
print(d.istitle())
False
True
True
True
The isupper() method returns True if all the characters are in upper case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax string.isupper()
In [9]:
txt = "THIS IS NOW!"
x = txt.isupper()
print(x)
True
In [10]:
a = "Hello World!"
b = "hello 123"
c = "MY NAME IS PETER"
print(a.isupper())
print(b.isupper())
print(c.isupper())
False
False
True
The join() method takes all items in an iterable and joins them into one string.
Syntax string.join(iterable)
Parameter Values iterable: Required. Any iterable object where all the returned values are strings
Note: When using a dictionary as an iterable, the returned values are the keys, not the values.
In [11]:
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)
John#Peter#Vicky
In [12]:
myDict = {"name": "John", "country": "Norway"}
mySeparator = "TEST"
x = mySeparator.join(myDict)
print(x)
nameTESTcountry
The ljust() method will left align the string, using a specified character (space is default) as the fill character.
Parameter Description length: Required. The length of the returned string character: Optional. A character to fill the missing space (to the right of the
string). Default is " " (space).
Example Return a 20 characters long, left justified version of the word "banana":
In [13]:
txt = "banana"
x = txt.ljust(20)
x = txt.ljust(20, "O")
print(x)
bananaOOOOOOOOOOOOOO
The lower() method returns a string where all characters are lower case.
Syntax string.lower()
In [ ]: Example
Lower case the string:
In [15]:
txt = "Hello my FRIENDS"
x = txt.lower()
print(x)
hello my friends
The lstrip() method removes any leading characters (space is the default leading character to remove)
Syntax string.lstrip(characters)
In [16]:
txt = " banana "
x = txt.lstrip()
In [17]:
txt = ",,,,,ssaaww.....banana"
x = txt.lstrip(",.asw")
print(x)
banana
The partition() method 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.
Note: This method searches for the first occurrence of the specified string.
Syntax string.partition(value)
ExampleGet your own Python Server Search for the word "bananas", and return a tuple with three elements:
1 - everything before the "match" 2 - the "match" 3 - everything after the "match"
In [18]:
txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x)
Example If the specified value is not found, the partition() method returns a tuple containing: 1 - the whole string, 2 - an empty string, 3 - an empty
string:
x = txt.partition("apples")
print(x)
The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.
Syntax string.rstrip(characters)
In [20]:
txt = " banana "
x = txt.rstrip()
In [21]:
txt = "banana,,,,,ssqqqww....."
x = txt.rstrip(",.qsw")
print(x)
banana
Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Parameter Description separator Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator maxsplit
Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences"
In [ ]:
Example
Split a string into a list where each word is a list item:
In [22]:
txt = "welcome to the jungle"
x = txt.split()
print(x)
In [25]:
txt = "hello, my name is Peter, I am 26 years old"
x = txt.split(" ,")
print(x)
x = txt.split("#")
print(x)
In [27]:
txt = "apple#banana#cherry#orange"
print(x)
['apple', 'banana#cherry#orange']
The splitlines() method splits a string into a list. The splitting is done at line breaks.
Syntax string.splitlines(keeplinebreaks)
Parameter Description keeplinebreaks Optional. Specifies if the line breaks should be included (True), or not (False). Default value is False
Example Split a string into a list where each line is a list item:
In [28]:
txt = "Thank you for the music\nWelcome to the jungle"
x = txt.splitlines()
print(x)
In [29]:
txt = "Thank you for the music\nWelcome to the jungle"
x = txt.splitlines(True)
print(x)
The startswith() method returns True if the string starts with the specified value, otherwise False.
Parameter Description value Required. The value to check if the string starts with. This value parameter can also be a tuple, then the method returns
true if the string starts with any of the tuple values. start Optional. An Integer specifying at which position to start the search end Optional. An Integer
specifying at which position to end the search
In [30]:
txt = "Hello, welcome to my world."
x = txt.startswith("Hello")
print(x)
True
In [31]:
txt = "Hello, welcome to my world."
x = txt.startswith("wel", 7, 20)
print(x)
True
Leading means at the beginning of the string, trailing means at the end.
You can specify which character(s) to remove, if not, any whitespaces will be removed.
Syntax string.strip(characters)
Example Remove spaces at the beginning and at the end of the string:
x = txt.strip()
x = txt.strip(",.grt")
print(x)
banana
The swapcase() method returns a string where all the upper case letters are lower case and vice versa.
Syntax string.swapcase()
Example Make the lower case letters upper case and the upper case letters lower case:
In [34]:
txt = "Hello My Name Is PETER"
x = txt.swapcase()
print(x)
The title() method returns a string where the first character in every word is upper case. Like a header, or a title.
If the word contains a number or a symbol, the first letter after that will be converted to upper case.
Syntax string.title()
In [35]:
txt = "Welcome to my world"
x = txt.title()
print(x)
Welcome To My World
x = txt.title()
print(x)
Example Note that the first letter after a non-alphabet letter is converted into a upper case letter:
x = txt.title()
print(x)
The upper() method returns a string where all characters are in upper case.
Syntax string.upper()
x = txt.upper()
print(x)
HELLO MY FRIENDS
The zfill() method 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.
Syntax string.zfill(len)
Parameter Description len Required. A number specifying the desired length of the string
In [39]:
txt = "50"
x = txt.zfill(10)
print(x)
0000000050
Example Fill the strings with zeros until they are 10 characters long:
In [40]:
a = "hello"
b = "welcome to the jungle"
c = "10.000"
print(a.zfill(10))
print(b.zfill(10))
print(c.zfill(10))
00000hello
welcome to the jungle
000010.000