Python Strings | Methods, Slicing, String Mutations, Exercises

4.7/5 - (6 votes)

In Python, You can define a string with either double quotes ” or single quotes ‘.

Strings in Python are arrays of bytes representing Unicode characters.

!!!Python does not have a character data type, a single character is simply a string with a length of 1.

my_text = “Welcome to webpedia”
my_text = ‘Welcome to webpedia’

With “\n” the following string will be displayed on a new line!

Multi-line Strings

The triple-quoted in Python can be used to represent a multi-line string.

Also, we can use triple quotes (i.e., a triplet of single quotes or triplet double-quotes) to represent the strings containing both single and double quotes to eliminate the need for escaping the string.

my_text = '''Nam accumsan feugiat nulla, id lacinia est imperdiet non.
Duis nunc neque, facilisis vel fringilla nec, ullamcorper gravida neque.
Quisque nec pretium "lacus". Integer facilisis mattis odio at congue.'''

//Nam accumsan feugiat nulla, id lacinia est imperdiet non.
Duis nunc neque, facilisis vel fringilla nec, ullamcorper gravida neque.
Quisque nec pretium "lacus". Integer facilisis mattis odio at congue.

How to access characters of a string in Python?

Individual characters in a string can be accessed by specifying the string name followed by the index number in square brackets([]).

  • The index value must be an integer and starts at zero
  • The index value can be an expression that is computed

How to use quotation marks in a string?

my_string = ‘”Welcome to webpedia”‘
my_string = “I’m going to learn python”

or You can use the backslash to escape quotes.

my_string = “\”Welcome to webpedia\””
my_string = ‘I\’m going to learn python’

Python String operations

String Concatenation

To concatenate, or combine, two strings use the + operator.

Example

a = “10”
b = “5”
c = a + b
What value will c have and what type?

15 (String)

Try to concatenate String with int, get an error:

str = '123' + 3
TypeError: can only concatenate str (not "int") to str

#convert from string to int:

str = int('123') + 3
//126

String Multiplication

You can use <strong>*</strong> to repeat strings
my_string = "hi"
print(my_string * 3)
# results hihihi

Slicing strings in Python

You can return a range of characters by using the slice syntax(specify the start index and the end index, separated by a colon, to return a part of the string).

If the second number is beyond the end of the string it stops at the end.

#Slice string
my_str = 'Welcome to webpedia'
print(my_str[2:6])
//lcom

If You leave off the first number or the last number of the slice, it is assumed to be the beginning or end of the string.

my_str = 'Welcome to webpedia'
print(my_str[11:])
//webpedia

How to reverse a String?

n = 'hello'
print(n[::-1])
//olleh

String Mutations

In Python, a string is immutable. You cannot overwrite the values of immutable objects.

How to make a change inside a string?

For example for the string = “webpedia” replace the 3rd character with “X”, “weXpedia”.
If you try directly, string[2] = “x”, you will get the next error:

TypeError: ‘str’ object does not support item assignment

Solution

One solution is to convert the string to a list and then change the value.
Use the join() string method to combine a list of strings into a single string. Specify a delimiter string ”.

The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.

string = "webpedia"
l = list(string)
l[2] = "X"
string = ''.join(l)
print(string)

//weXpedia

Solution

Another solution is to slice the string and join it back.

string = "webpedia"
string = string[:2] + "X" + string[3:]
print(string)

//weXpedia

String Comparation

my_str = 'web'
if my_str == 'web':
    print('ok')
//ok

Uppercase letters are generally less than lowercase letters.

All uppercase letters come before all lowercase letters, so be careful when sorting a list of words!

if 'XYZ' < 'abc':
    print('TRUE')
//TRUE

How to get length of a string?

To get the length of a string, use the len() function.

Len() is like print(), a built in function.

my_string = "Welcome to webpedia"
print(len(my_string))
# 19

What does the len() function return when it receives an int instead of a string?

TypeError: object of type ‘int’ has no len()

my_string = "Welcome to webpedia"
print(len(my_string))
#19

Python String Methods

String Methods in Python behaves similarly to a function. Methods are functions that below to objects.

Methods are functions that are called using dot notation.

!!Methods do not modify the original strings, instead they return a new string that has been altered.

my_str = 'Hi Webpedia'
print(my_str.lower())
//hi webpedia
print(my_str)
//Hi Webpedia

strip() method

The strip() method removes any whitespace from the beginning or the end.

my_string = " Welcome to webpedia "
print(a.strip()) 
# "Welcome to webpedia"

lstrip() or rstrip() remove whitespace at the left or right!

lower() method

The lower() method returns the string in lower case:

my_string = "Welcome to webpedia"
print(my_string .lower())
# "welcome to webpedia"

format() method

The format() method formats the specified value(s) and insert them inside the string’s placeholder.
The placeholder is defined using curly brackets: {}.

print("{} reasons to learn Python".format(10))
# 10 reasons to learn Python

How to print a float with two decimal places in Python?

Format the float with two decimal places:

float_num = 3.14159265358
formatted_float = "{:.2f}".format(float_num)
print(formatted_float)
//3.14

split() method

The split() method splits a string into a list of strings.
Read here about Python Lists, Operations & methods

You can specify the separator, the default separator is any whitespace.

Also multiple spaces do not matter, they are treated as a single space.

my_str = "reasons to learn Python"
print(my_str.split())
# ['reasons', 'to', 'learn', 'Python']

Methods may or may not have arguments

Each of these methods accepts the string itself as the first argument of the method. However, they also could receive additional arguments, that are passed inside the parentheses, like:

replace() method

The replace() method search and replaces a string with another string:

my_string = "Welcome to webpedia"
print(my_string .replace("Welcome", "Hi"))
# "Hi to webpedia"

It replaces all occurrences of the search string with the replacement string.

find() method

The find() method finds the first occurrence of the specified value or -1 if the value is not found.

The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found.

my_str = "reasons to learn Python"
print(my_str.find('learn'))
# 11

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

subscribe youtube

Leave a Comment

WebPedia.net