Python String With Examples

This article entitle Python String is a continuation of the previous article entitled Python Number.

Python Strings are one of the most used and popular data types we can easily create a string by enclosing the characters in single or double quotes.

What is String in Python?

In Python, a string is an immutable data type that cannot be changed once they are already created since the strings is cannot be changed the only way to change it is to construct a new string.

Example

stringOne = 'Hello World By SOURCECODEHERO!'
stringTwo = "Python Tutorial For True Heroes"

Accessing String Characters in Python

To access the values or individual characters in a string we can use three different ways negative indexing, indexing, and slicing.

Negative indexing in Python is very similar to a list which allows to index of the given format string representation.

Example

name = 'Glenn'

# access 3th last element
print(name[-3]) # "e"

Output

e

Indexing is one of the ways to treat a string as a list and simply use the index values.

Example

name = 'Glenn'

# access 3th last element
print(name[3]) # "n"

Output

n

The slicing operator ( : ) colon can be used to access a range of characters in a string.

Example

name = 'Glenn'

# access character from 1st index to 3rd index
print(name[1:3]) # "le"

Output

le

Take Note: In some instances that you want to access an index that is out of range or a number that uses other than an integer, we will get an error in Python.

Updating Strings in Python

In some instances where you want to update an existing string object, you can use the ‘update’ and reassign a variable and set a new string. You can create a value that is related to the previous value or else a totally different string together.

Example

stringOne = 'Hello Python!'
print ("Updated String :- ", stringOne[:6] + 'Heroes')

Output

Updated String :-  Hello Heroes

Multiline String in Python

To create a multiline string in Python we can simply use the triple single quotes (”’) or triple quotes (“””).

Example

# multiline string 
greetings = '''
If you want a free source code and tutorials
sourcecodehero is always here for you
'''

print(greetings)

Output

If you want a free source code and tutorials
sourcecodehero is always here for you

String Operations in Python

There are many operations that can be used to perform with a string that can make it one of the most useful data types in Python.

To compare two strings we can simply use the == operator once the two strings are equal the operators will return true otherwise will return false.

Example

stringOne = "Hello, world!"
stringTwo = "I love Python."
stringThree = "Hello, world!"

# compare stringOne and stringThree
print(stringOne == stringTwo)

# compare stringOne and stringThree
print(stringOne == stringThree)

Output

False
True

Join two or more strings in Python

To join two or more strings we can simply join it with a concatenate using a plus (+) operator.

Example

greetings = "Hi, "
name = "Jack"

# using + operator
results = greetings + name
print(results)

# Output: Hi, Jack

Output

Hi, Jack

String Length in Python

To find the length of the string we can simply use the len() method.

Example

name = 'Glenn'

# count length of name string
print(len(name))

# Output: 5

Output

5

Iterate a string in Python

Using a for loop we can easily iterate a given template string.

Example

name = 'Glenn'

# iterating through name string
for iterate in name:
    print(iterate)

Output

G
l
e
n
n

String membership test in Python

Using the ( in ) keyword we can easily test once if the substring was exist within the string or none.

Example

print('r' in 'sourcecodehero') # True
print('al' not in 'tutorial') #False

Output

True
False

Python Escape Sequences

The following list is all escape sequences that are supported by Python

Escape SequenceDescription
\\Backslash
\'Single quote
\"Double quote
\aASCII Bell
\bASCII Backspace
\fASCII Formfeed
\nASCII Linefeed
\rASCII Carriage Return
\tASCII Horizontal Tab
\vASCII Vertical Tab
\oooA character with octal value ooo
\xHHA character with hexadecimal value HH

An escape sequence is mostly used for escaping some of the whitespace characters that are present within the string. Supposed that we need to add both single quotes and double quotes within the string.

Example

words = "She said, "How are you?""

print(words) # throws error

Since the strings were represented by a double or a single quote, The Python compiler will read the “She said” as a string and the above program will result in an error.

In order to solve this type of error we will use the escape character ( \ ) to escape and run the program correctly.

# escape double quotes
greetings = "She said, \"How's your day?\""

# escape single quotes
greetings = 'She said, "How\'s your day?"'

print(greetings)

Output

She said, "How's your day?"

String methods in Python

Aside from the mentioned above, there is still a number of string format methods that are present in Python. The following are some of the methods below.

MethodsDescription
upper()converts the string to uppercase
lower()converts the string to lowercase
partition()returns a tuple
replace()replaces substring inside
find()returns the index of first occurrence of substring
rstrip()removes trailing characters
split()splits string from left
startswith()checks if string starts with the specified string
isnumeric()checks numeric characters
index()returns index of substring

String formatting or (f-Strings) can be used to print variables and values in an easy way.

Example

name = 'Glenn'
country = 'Philippines'

print(f'{name} is from {country}')

Output

Glenn is from Philippines

Summary

In summary, you have read about Python String. We also discussed in this article what is String in Python, accessing string characters, updating strings, multiline strings, string operations, joining two or more strings, string length, iterating a string, string membership test, escape sequences, and string methods.

I hope this article about String in Python programming language could help you a lot to continue pursuing learning this powerful programming language.

If you want to learn more check out my previous and latest articles for more career-changing articles.

Leave a Comment