String Manipulation in Python

Estimated reading time: 2 minutes

Are you working with strings and need to quickly alter them so they look correct? We are going to take you through the following manipulations so you can quickly upskill on how to better manage them.

Python offers some very easy to use methods, which make the process of getting what you want the data to look like easier.

Find the length of a string

# Find the length of a string
text = "Fetchme"
print("Length is:", len(text))

result is: ===> Length is: 7

How to split a string variable – using one split value

text = "Hello,what is your name."
splittext = text.split(",") ==> One split value assigned.
print(splittext)

result is: ===> ['Hello', 'what is your name.']

How to split a string variable – use more than one split value

text = "Hello,what is your name;My name is joe;test"
print(re.split(r'[,.;]', text)) ==> Notice that what you want to split on is between the [] brackets.

result is: ===> ['Hello', 'what is your name', 'My name is joe', 'test']

Find any character in a string

text = "Hello,what is your name."
print("First character is:", text[0])
print("Fifth character is:", text[5])
print("Sixth character is:", text[6])

result:
First character is: H
Fifth character is: ,
Sixth character is: w

Print a string in an upper or lower case

text = "Joe"
print("Upper case:", str.upper(text)) #upper case
print("Lower case:",str.lower(text)) #lower case

result:
Upper case: JOE
Lower case: joe

Concatenation of a string

first = "rainy"
last = "day"
name = first + last
print(name)

the result is: rainyday

Testing a string value returns a Boolean value

testword = "abc123XSWb"
digits = "123"
print(testword.isalnum()) #check if all characters are alphanumeric
print(testword.isalpha()) #check if all characters in the string are alphabetic
print(digits.isdigit()) #test if string contains digits only
print(testword.istitle()) #test if string contains title words
print(testword.isupper()) #test if string contains upper case
print(testword.islower()) #test if string contains lower case
print(testword.isspace()) #test if string contains spaces
print(testword.endswith('b')) #test if string endswith a b
print(testword.startswith('H')) #test if string startswith H

result:
True
False
True
False
False
False
False
True
False

python sort method

Estimated reading time: 2 minutes

Why would you sort a list?

It allows efficiency in other algorithms to quickly find data in the list that is used as an input to their code, examples include searching and merging data.

Also, can be used to standardize the data set so that it can have a meaningful representation.

For data visualization purposes having it in order can allow the viewer quickly to attach meaning to what they see in front of them.

There are different sorting techniques as follows:

  • Bubble Sort Algorithm is used to arrange N elements in ascending order.
  • Selection sort is a straightforward process of sorting values. In this method, you sort the data in ascending order.
  • Merge sort splits two lists into a comparable size, sorts them, and then merges them back together.

According to the  Python Organisation website, Python lists have a built-in list.sort() the method that modifies the list in-place.

mylist = [5, 2, 3, 1, 4]
mylist.sort()
print(mylist)
[1, 2, 3, 4, 5]

This method only works for lists.

It also has a very similar method sorted() , which, unlike list.sort, can work on any iterable.

a= {'c':'1','b':'2','a':'3'}

print(sorted(a))
['a', 'b', 'c']

Note that the sorted method only sorts the key value in the dictionary above.

Per programiz.com parameters for the sorted() function are as follows:

sorted() can take a maximum of three parameters:

  • iterable – A sequence (stringtuplelist) or collection (setdictionaryfrozen set) or any other iterator.
  • reverse (Optional) – If, the sorted list is reversed (or sorted in descending order). Defaults to if not provided.
  • key (Optional) – A function that serves as a key for the sort comparison. Defaults to None.

Click how to sort lists in python to get a video tutorial on the above, which may help to explain the concepts further.