Predictive Hacks

# Python String Tutorial

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.

## Escape Sequence

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

### Get updates and learn from the best

Python

#### A Tutorial about Market Basket Analysis in Python

What is Market Basket Analysis Intuitively, we could say that the Market Basket Analysis is given a database of customer

Python

#### Item-Based Collaborative Filtering in Python

In another post, we explained how we can easily apply advanced Recommender Systems. In this post we will provide an