String operations in Python

This is a quick documentation on Python string operations.

Writing string to variable (assignment) using equal (=) operator
a = "test string"
print(a)
test string
Line-breaks within a string (multi-line string) using three quotes
b = """This is first line, 
second line, 
thrid line"""
print(b)
This is first line, 
second line, 
thrid line
Strings can be handled as if they were lists
c = "this is a string"
for i in range(0,len(c)):
    print(c[i])
t
h
i
s
 
i
s
 
a
 
s
t
r
i
n
g
Strings can be sliced, similar to when working with lists or NumPy arrays
print(c[5:10])
is a 
And, again similar to lists and NumPy arrays, characters within a string can be accessed using negative indexing
print(c[-6:-3])
str
print(c[-1])
g
The length of a string can be determined using the len() function
len("abc")
3
In addition, the string class itself has a series of methods; one of them is lower(), converting all characters in the string to lower case
"ABC".lower()
'abc'
upper() on the other hand converts all characters in the string to upper case
"aBc".upper()
'ABC'
replace() can be used for replacing sub-strings or single characters within a string with other strings or characters
"test string".replace("test","confirmed")
'confirmed string'
"aaaa".replace("a","e")
'eeee'
"aa".replace("a","-d-")
'-d--d-'
split() is a method that splits a string into a list of sub-strings, splitting at defined character within the string
strList = "this,is,a,string,with,commas".split(",")
for i in strList:
    print(i)
this
is
a
string
with
commas
“in” operator can be used for conducting a logic test with strings, testing wether a given sub-string is contained by some string being tested
"x" in "abc"
False
"a" in "abc"
True
"a" in "ABC"
False
“not in” operator is the negated version of the “in” operator
"x" not in "abc"
True
In Python, strings can be concatenated using the + operator
print("this " + "is " + "a " + "long " + "string ")
this is a long string 
a = "part 1 "
b = "part 2 "
print(a+b)
part 1 part 2 
The format() method formats its input arguments into string and inserts them into {}-placeholders
"this is a string with a placeholder here: {}".format(100)
'this is a string with a placeholder here: 100'
"number 1: {}, number 2: {}, and the rest: {}".format(20.33,30,5000)
'number 1: 20.33, number 2: 30, and the rest: 5000'
# using index numbers inside the {} placeholders even allows a defined mapping of values to palceholders
"number 1: {1} number 2: {0}".format(1,2)
'number 1: 2 number 2: 1'
"number 1: {1} number 2: {0}".format(2,1)
'number 1: 1 number 2: 2'
Characters that by default are not permitted within a string can be added using the “\” (escape) operator
print("this is a \"test\" in wether the escape operator works")
this is a "test" in wether the escape operator works

In above line the \” escape operation is applied; there are multiple other forms of “escape” operations in Python strings. Here are some exampels:

# \\ adds a backslash
print("this is a backslash: \\")
this is a backslash: \
# \n adds a new line
print("first line\nsecond line")
first line
second line
# \t  adds a tab
print("first part\tsecond part")
first part	second part

There are a wide range of additional string methods. This is the list of all methods in the Python string class.

Below you find some more examples. A complete overview can be found here: https://www.w3schools.com/python/python_strings.asp

# capitalize() transforms first character into upper letter
"abc".capitalize()
'Abc'
# count() counts the frequency of some search term within the given string
"a b a b a a a".count("a")
5

You May Also Like

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.