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
3 min readSep 10

--

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'…

--

--

Python: iter, enumerate, zip

3 min read

Oct 9

Python: Exception Handling

3 min read

Oct 9

Python: remove() and pop()

3 min read

Oct 6

Python: update() method of dictionary

2 min read

Apr 16

Tail recusion and tail recursive elimination

2 min read

Apr 10

Python -1

1 min read

Apr 1

Python: Local, Nonlocal and Global variables

2 min read

Sep 27

Python: GIL (Global Interpreter Lock)

2 min read

Sep 27

Python: Deep and Shallow Copy

2 min read

Sep 25

Python: range(), numpy.arange(), and numpy.linspace()

3 min read

Sep 9

Rahul S

I learn as I write | LLM, NLP, Statistics, ML