Predictive Hacks

Python String Tutorial

strings

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. Square brackets can be used to access elements of the string.

Let’s start with our string example “hello, predictive hacks!“:

s="hello, predictive hacks!"
print(s)
hello, predictive hacks!
# get the data type
type(s)
str
# get the length of the string
len(s)
24

Concatenate

We can easily concatenate strings by simply adding them

"hello"+" "+"world"
'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.

s[2:6]
'llo,'
# get the first 5 characters
s[:5]
'hello'
# get the 7th character up to the end 
s[7:]
'predictive hacks!'
# get the last character
s[-1]
!
# get the 3 last characters
s[-3:]
'ks!'
# Get the characters from position 5 to position 1, starting the count from the end of the string:
s[-5:-2]
'ack'
# get the reverse string i.e. palindrome
s[::-1]
'!skcah evitciderp ,olleh'
# get all the even position characters like 0,2,..., up to the end of the string
s[0::2]
'hlo rdciehcs'

Changing Case

We can use methods to capitalize the first word of a string, change cases to upper and lower case strings.

# Capitalize first letter in string
s.capitalize()
'Hello, predictive hacks!'
# Capitalize the starting letter of each word
s.title()
'Hello, Predictive Hacks!'
s.upper() 
# s.lower() for lower case
'HELLO, PREDICTIVE HACKS!'

Location and Counting

We can count the number of particular characters as well as to find the location of a string

s.count('e')
3
# find the location of the first occurence
s.find('e')
1

Formatting

The center() method allows you to place your string ‘centered’ between a provided string with a certain length and the expandtabs() will expand tab notations \t into spaces:

s.center(50,'#')
'#############hello, predictive hacks!#############'
'hello\thi'.expandtabs()
'hello   hi'

is check methods

These various methods below check it the string is some case. Some of these methods are the isalnum() which will return true if all characters in the string are alphanumeric, isalpha() which will return True if all characters are alphanumeric, islower() which will return True if all characters are lowercase and startswith() which checks if the string starts with these characters.

s.isalnum()
False
s.islower()
True
s.startswith('hell')
True

Built-in Reg. Expressions

Strings have some built-in methods that can resemble regular expression operations. We can use split() to split the string at a certain element and return a list of the result. We can use partition to return a tuple that includes the separator (the first occurrence) and the first half and the end half.

s.split(' ')
['hello,', 'predictive', 'hacks!']
s.split(" ", maxsplit=1)
['hello,', 'predictive hacks!']
s.rsplit(" ", maxsplit=1)
['hello, predictive', 'hacks!']
s.partition('predictive')
('hello, ', 'predictive', ' hacks!')

Joining

You can also join a list of strings:

my_list=["This", "is","my","string"]
" ".join(my_list)
'This is my string'

Replace

We can replace part of string:

s.replace("hello","hi")
'hi, predictive hacks!'

strip

We can strip the white spaces of the string using the strip() (or the rstrip() or strip()), however, we can specify and a specific character to strip.

s.strip("!")
'hello, predictive hacks'

String Formatting

We will give some examples of string formatting.

The following example summarizes string formatting options in Python.

name = 'George'
age = 35

print('%s is %d years old' % (name, age))
print('{} is {} years old'.format(name, age))
print(f'{name} is {age} years old')
George is 35 years old
George is 35 years old
George is 35 years old

Calling by its name

# Create a dictionary
my_dict = {"field": 'Data Science',
           "tool": 'Python'
        }

# Complete the placeholders accessing elements of field and tool keys
my_string = "If you are interested in {data[field]}, you can take the course related to {data[tool]}"

# Use dictionary to replace placeholders
print(my_string.format(data=my_dict))
If you are interested in Data Science, you can take the course related to Python
# Import datetime 
from datetime import datetime

# Assign date to get_date
get_date = datetime.now()

# Add named placeholders with format specifiers
message = "Good afternoon. Today is {today:%B %d, %Y}. It's {today:%H:%M} o'clock"

# Format date
print(message.format(today=get_date))
Good afternoon. Today is June 05, 2020. It's 19:34 o'clock

f-string example:

# Complete the f-string
color = "brown"
animal1="fox"
animal2="dog"
print(f"the quick {color} {animal1} jumps over the lazy {animal2}")
the quick brown fox jumps over the lazy dog

f-string dictionaries

user = {'name': 'George Pipis', 'job': 'Data Scientist'}

print(f"{user['name']} is a {user['job']}")
Geoge Pipis is a Data Scientist
number1 = 120
number2 = 7

# Include both variables and the result of dividing them 
print(f"{number1} tweets were downloaded in {number2} minutes indicating a speed of {number1/number2:.1f} tweets per min")
120 tweets were downloaded in 7 minutes indicating a speed of 17.1 tweets per min

You can find more examples of the f-string.

Below we represent a list of the string methods and the escape sequences.

String Methods

Here is a list of all the string methods.

MethodDescription
capitalize()Converts the first character to upper case
casefold()Converts string into lower case
center()Returns a centered 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
index()Searches the string for a specified value and returns the position of where it was found
isalnum()Returns True if all characters in the string are alphanumeric
isalpha()Returns True if all characters in the string are in the alphabet
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
islower()Returns True if all characters in the string are lower case
isnumeric()Returns True if all characters in the string are numeric
isprintable()Returns True if all characters in the string are printable
isspace()Returns True if all characters in the string are whitespaces
istitle()Returns True if the string follows the rules of a title
isupper()Returns True if all characters in the string are upper case
join()Joins the elements of an iterable to the end of the string
ljust()Returns a left-justified version of the string
lower()Converts a string into lower case
lstrip()Returns a left trim version of the string
maketrans()Returns a translation table to be used in translations
partition()Returns a tuple where the string is parted into three parts
replace()Returns a string where a specified value is replaced with a specified value
rfind()Searches the string for a specified value and returns the last position of where it was found
rindex()Searches the string for a specified value and returns the last position of where it was found
rjust()Returns a right justified version of the string
rpartition()Returns a tuple where the string is parted into three parts
rsplit()Splits the string at the specified separator, and returns a list
rstrip()Returns a right trim version of the string
split()Splits the string at the specified separator, and returns a list
splitlines()Splits the string at line breaks and returns a list
startswith()Returns true if the string starts with the specified value
strip()Returns a trimmed version of the string
swapcase()Swaps cases, lower case becomes upper case and vice versa
title()Converts the first character of each word to upper case
translate()Returns a translated string
upper()Converts a string into upper case
zfill()Fills the string with a specified number of 0 values at the beginning

Escape Sequence

Here is a list of all the escape sequences supported by Python.

Escape SequenceDescription
\newlineBackslash and newline ignored
\\Backslash
\’Single quote
\”Double quote
\aASCII Bell
\bASCII Backspace
\fASCII Formfeed
\nASCII Linefeed
\rASCII Carriage Return
\tASCII Horizontal Tab
\vASCII Vertical Tab
\oooCharacter with octal value ooo
\xHHCharacter with hexadecimal value HH

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

letter frequency
Python

Document Letter Frequency in Python

Letter Frequency We will provide you a walk-through example of how you can easily get the letter frequency in documents

[the_ad_group id="232"]
[the_ad id="2133"]