19
loading...
This website collects cookies to deliver better user experience
my_string = 'Codementor'
print(my_string)
my_string = "Codementor"
print(my_string)
my_string = '''Codementor'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Welcome to Codementor,
find a Python expert to help you learn Python!"""
print(my_string)
Codementor
Codementor
Codementor
Welcome to Codementor,
find a Python expert to help you learn Python!
my_string
, we’ll simply name our Python string s
in the next section.-1
refers to the last item, -2 to the second last item, and so on. If you want to access a range of items in a string, you can use the slicing operator, :
.s = 'Codementor'
print(s[0])
print(s[1])
print(s[2])
print(s[3])
print(s[4])
print(s[5])
print(s[6])
print(s[7])
print(s[8])
print(s[9])
C
o
d
e
m
e
n
t
o
r
s = 'Codementor'
print(s[-10])
print(s[-9])
print(s[-8])
print(s[-7])
print(s[-6])
print(s[-5])
print(s[-4])
print(s[-3])
print(s[-2])
print(s[-1])
s = 'Codementor'
print(s[:])
print(s[:4])
print(s[-6:])
print(s[2:5])
Codementor
Code
mentor
dem
capitalize()
, lower()
, upper()
, join()
, split()
, find()
, and replace()
. Python format()
is another powerful and frequently used Python string method. However, due to its complexity, we will not cover it here. Feel free to learn more about format()
from Python’s official documentation!capitalize()
string method is used when you want to capitalize the first character of a string of text. Here’s an example:s = "codementor speeds up your python learning process"
x = s.capitalize()
print (x)
Codementor speeds up your python learning process
lower()
Python string method is the opposite of upper()
. It turns all of the characters in a string into lowercase letters.s = "CODEMENTOR HELPS solve your CODING problems!"
x = s.lower()
print(x)
codementor helps solve your coding problems!
upper()
Python string method is the opposite of lower()
. It turns all of the characters in a string into uppercase letters.s = "codementor has the best python tutors!"
x = s.upper()
print(x)
CODEMENTOR HAS THE BEST PYTHON TUTORS!
join()
method takes all items in an iterable and joins them into one string. For example, you can join items in a tuple or in a dictionary. Let’s say you want to put all your party guests’ into a string, you can use the following code and join()
method to combine and create the list.PartyGuests = ("Anna", "Allie", "Joy", "Chloe", "Ellyn")
x = ", ".join(PartyGuests)
print(x)
Anna, Allie, Joy, Chloe, Ellyn
split()
method splits a Python string into a list. You can specify the separator, but the default separator is any whitespace.split()
works:txt = "Find Python Help on Codementor Today"
x = txt.split()
print(x)
['Find', 'Python', 'Help', 'on', 'Codementor', 'Today']
split()
divides a Python string in a list into single items. However, you may split the string into a list with a maximum of 2 items. Here’s how that could work, using # as the separator:txt = "best#way#to#learn#python#is#to#find#a#mentor"
x = txt.split("#", 5)
print(x)
['best', 'way', 'to', 'learn', 'python', 'is#to#find#a#mentor']
find()
method is used to find a specified value’s first appearance in a string. It is almost identical to the index()
method, except when a value cannot be found. Instead of displaying -1
, the index()
method displays ValueError: substring not found
.txt = "Codementor"
x = txt.find("e", 4, 8)
print(x)
5
. Normally, find()
would find the first appearance of “e” in the string, which would be 3 in our example. However, in the example above, it asked for “e” between position 4 and 8, which is why our output is 5
.replace()
method is used to replace a specified phrase with another specified phrase. Unless otherwise specified, all specified phrases in the Python string will be replaced. replace()
:str = "I love office work because office work is the best."
x = str.replace("office", "remote")
print(x)
I love remote work because remote work is the best
replace()
if we only want to replace one of the words in a Python string:str = "I love office work but going into the office to bond with my colleagues can be fun!"
x = str.replace("office", "remote", 1)
print(x)
I love remote work but going into the office to bond with my colleagues can be fun!
1
, we’ve replaced the first occurrence of the word “office.”format()
is an extremely important and super powerful Python string method, we will dedicate another article to format()
. You can find a list of all the Python string methods in the reference section! list=[‘a’,’b’,’c’]
list=[‘America’,’India’,’Taiwan’]
list=[1,2,3,4,5]
list=[2,"America",5.2,"b"]
join()
Python string methodjoin()
Python string methodmap()
Python string methodjoin()
method can create strings with iterable objects. The element of an iterable (i.e. list, string, and tuple) can be joined by a string separator to return a new concatenated string.string.join(iterable)
inp_list = ['Coding', 'for', 'Everyone']
out_str = " "
print(out_str.join(inp_list))
Coding for Everyone
join()
method to convert a Python list to string works as long as the passed iterable contains string elements. However, if the list contains both string and integer as its element, we’d need to convert elements to string while adding to string. This is where using list comprehension along with join()
comes in handy.from builtins import str
inp_list = ['There', 'are', 'more', 'than', 10000, 'mentors', 'who', 'can', 'help', 'you', 'learn', 'Python', 'on', 'Codementor']
listToStr = ' '.join([str(elem) for elem in inp_list])
print(listToStr)
There are more than 10000 mentors who can help you with Python on Codementor
string()
method, the map()
function accepts functions and iterable objects, like lists, types, strings, etc. The map()
function maps the elements of the iterable with the function provided.map(function, iterable)
map()
function, every element of the iterable (list) is mapped onto a given function to generate a list of elements. We’ll then use the join()
method to display the output in string form:inp_list = ['Get', 'Python', 'help', 'in', 'less', 'than', 6, 'minutes', 'on', 'Codementor']
listToStr = ' '.join(map(str, inp_list))
print(listToStr)
Get Python help in less than 6 minutes on Codementor
# Function to convert
def listToString(s):
out_str = ""
# traverse in the string
for ele in inp_str:
out_str += ele
# return string
return out_str
# Driver code
inp_str = ['Codementor', 'is', 'AWESOME']
print(listToString(inp_str))
CodementorisAWESOME
str()
function. With that said, there are four ways of converting Python int to string. The examples we provide below apply to Python 3.str()
function.format()
functionstr(integer_value)
num = 100
print(type(num))
converted_num = str(num)
print(type(converted_num))
“%s” % integer
num = 100
print(type(num))
converted_num = "% s" % num
print(type(converted_num))
‘{}’.format(integer)
num = 100
print(type(num))
converted_num = "{}".format(num)
print(type(converted_num))
f'{integer}’
num = 100
print(type(num))
converted_num = f'{num}'
print(type(converted_num))
mentor_count = 30
print(type(mentor_count))
converted_num = str(mentor_count)
print("The number of mentors I have worked with in the last month: " + str(mentor_count))
<class ‘int’>
The number of mentors I have worked with in the last month: 30
decode()
methodstr()
functioncodec.decode()
methoddecode()
method allows developers to convert an argument string from one encoding scheme to another.import string
data = b'Codementor'
print('\nInput:')
print(data)
print(type(data))
output = data.decode()
print('\nOutput:')
print(output)
print(type(output))
Input:
b'Codementor'
<class 'bytes'>
Output:
Codementor
<class 'str'>
str()
function of Python returns the string version of the object.data = b'Codementor'
print('\nInput:')
print(data)
print(type(data))
output = str(data, 'UTF-8')
print('\nOutput:')
print(output)
print(type(output))
Input:
b'Codementor'
<class 'bytes'>
Output:
Codementor
<class 'str'>
import codecs
data = b'Codementor'
print('\nInput:')
print(data)
print(type(data))
output = codecs.decode(data)
print('\nOutput:')
print(output)
print(type(output))
Input:
b'Codementor'
<class 'bytes'>
Output:
Codementor
<class 'str'>
datetime.strftime()
function. What is tricky is that there are many different ways to showcase datetime, thus presenting developers the challenge of knowing when to use what format code. datetime.strftime()
function, you can turn the current datetime object into different string formats:from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)
year: 2021
month: 07
day: 09
time: 05:22:21
date and time: 07/09/2021, 05:22:21
from datetime import datetime
timestamp = 1625834088
date_time = datetime.fromtimestamp(timestamp)
print("Date time object:", date_time)
d = date_time.strftime("%m/%d/%Y, %H:%M:%S")
print("Date and time:", d)
d = date_time.strftime("%d %b, %Y")
print("Shortened date:", d)
d = date_time.strftime("%d %B, %Y")
print("Full date:", d)
d = date_time.strftime("%I%p")
print("Hour of day:", d)
Date time object: 2021-07-09 12:34:48
Date and time: 07/09/2021, 12:34:48
Shortened date: 09 Jul, 2021
Full date: 09 July, 2021
Hour of day: 12PM
Python String Method | Description |
---|---|
casefold() | Similar to lower() , Converts string to lower cases. |
center() | Centers the string output. |
count() | Count how many times a variable appeared in a string. |
encode() | Encodes the string, using the specified encoding. If unspecified, UTF-8 will be used. |
endswith() | Returns true if the string ends with the specified value. |
expandtabs() | Uses \t to create spaces between characters. |
format() | Formats specified values in a string. |
format_map() | Similar to format()
|
index() | Searches the string for a specified value and returns the position of where the value is. If the value is a word in a string of sentence, the index will be the number of the first character of the word. |
isalnum() | Returns True if all characters in the string are alphabets and numeric. If there’s a space in the string, you’d get False. |
isalpha() | Returns True if all the characters in the string are in the alphabet. Characters like ë are considered alphabets. Applies to all languages. |
isdecimal() | Returns True if all characters in the string are decimals |
isdigit() | Returns True if all characters in the string are digits |
isidentifier() | Returns True if the string is an identifier. Identifiers can only contain alphanumeric letters or underscores. An identifier can’t start with a number, or contain any spaces. |
islower() | Returns True if all characters are lowercase. |
isnumeric() | Returns True if all characters are numeric. |
isprintable() | Returns True if all characters in the string are printable. |
isspace() | Returns True if all characters are whitespaces. |
istitle() | Returns True if the string follows the rules of a title, which means all words start with an uppercase letter and the rest are lowercase letters. |
isupper() | Returns True if all characters in the string are upper case. |
ljust() | Left aligns the specified string characters and uses numbers to indicate the amount of space to separate specified variables from other characters or sentences. |
maketrans() | Used to replace characters with specified characters. |
partition() | Searches for a specified string, and splits the string into a tuple containing three elements. The specified element will be the second element, and the first and third will be what comes before and after the specified element. |
replace() | Replaces the specified value in the string with another specified value in the new string. |
rfind() | Searches the string for a specified value and returns the last position of where it was found. The index will be the number of the first character of the specified value. |
rindex() | Searches the string for a specified variable and returns the last position of where it was found. The index will be the number of the first character of the specified variable. |
rjust() | Returns a right justified version of the string. Opposite of ljust() . |
rpartition() | Similar to partition() . |
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. |
rstrip() | Removes any spaces or trailing characters that are specified. |
split() | Splits a string into a list. The default separator is any whitespace, but the separator can be specified (i.e. , ). |
splitlines() | Uses \n to split the string into a list. |
startswith() | Returns True if the string starts with the specified value. |
strip() | Removes any leading and trailing characters of the specified variables. Unless otherwise specified, the default trailing characters are whitespaces. |
swapcase() | Swaps all the characters in a string. If the character is an uppercase letter, it’ll turn into a lowercase letter, and vice versa. |
title() | Converts the first character of each word to uppercase. |
translate() | Returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table. |
zfill() | Adds zeros (0) at the beginning of the string, until it reaches the specified length. |
Format Code | Description | Example |
---|---|---|
%d | Day of the month as zero-padded numbers | 01, 02, 03, 04 …, 31 |
%a | Abbreviated weekday | Sun, Mon, Wed, ..., Sat |
%A | Full weekday name | Sunday, Monday, …, Saturday |
%m | Month as zero-padded numbers | 01, 02, 03, …, 12 |
%b | Abbreviated month | Jan, Feb, … Dec |
%B | Full month name | January, February, …, December |
%y | Year without century | 00, 01, 02, …, 99 |
%Y | Year with century | 0001, …, 2021, …, 9999 |
%H | 24-hr clock hour | 01, 02, 03, …, 23 |
%M | Minute as zero-padded numbers | 01, 02, …, 59 |
%S | Second as zero-passed numbers | 01, 02, …, 59 |
%f | Microsecond, zero-padded on the left | 000000, 000001, …, 999999 |
%l | 12-hr clock hour | 01, 02, …, 12 |
%p | Location’s AM or PM | AM, PM |
%j | Day of the year | 01, 02, 03, …, 366 |