Python: STRING cheatsheet

This article provides a comprehensive Python string manipulation cheatsheet, covering essential functions like substring checks, capitalization, replacing text, splitting strings, and checking character types. It offers clear examples and explanations, making it a valuable resource for anyone working with strings in Python.

Rahul S

--

word = 'Rahul'
sentence = 'My name is Rahul Sharma'
if word in sentence:
print("The word is in the sentence.")
else:
print("The word is not in the sentence.")

# Converting into lower and upper
print(f"The uppercase 'word' is {word.upper()}")
print(f"The lowercase 'word' is {word.lower()}")

#output = The word is in the sentence.
# The uppercase 'word' is RAHUL
# The lowercase 'word' is rahul
# .strip()
# Removing leading and trailing whitespaces.

string = " I am Anthony Gondalves. .. "
string.strip()

# output = 'I am Anthony Gondalves. ..'
#' '.join(my_list) - Joining the elements of a list into a single string 
#with a space delimiter.

li = ['happy','no','1','39784830','Okie Dokie']
output = " ".join(li)
print(output)

# output = happy no 1 39784830 Okie Dokie
#' '.join(my_list) - Joining the elements of a list into a single string 
#with a comma delimiter.

li = ['happy','no','1','39784830','Okie Dokie']
output = ",".join(li)
print(output)

# output = happy,no,1,39784830,Okie Dokie
#str.split(): Splits a string into a list of substrings based on a delimiter (comma). 
str = 'happy,no,1,39784830,Okie Dokie'
li = str.split(',')
print(li)

#output = ['happy', 'no', '1', '39784830', 'Okie Dokie']
#str.split(): Splits a string into a list of substrings based on a delimiter (space).
str = "happy no 1 39784830 Okie Dokie"
li= str.split(" ")
print(li)

#output = ['happy', 'no', '1', '39784830', 'Okie Dokie']
# new_string = my_string.replace(old, new) - Replacing occurrences of a substring.
#this is an inplace operation and affect the objects directly.

string = 'We are all dead. We do not belong to the world. We will never die, because we are mortal'…

--

--