Python Strings

Here, we have learnt about python strings, how to create python strings, access characters in string, string slicing, deleting/updating a string....

In this article, we'll discuss about Python Strings, how to create python strings, access characters in string, string slicing, deleting/updating a string, formatting of strings and escape sequencing.

Python Strings

What are Python Strings?

Strings are the most popular data type of python programming language. Strings are the collection or sequence of characters which are written within the single quotes, double quotes or triple quotes. Computer doesn't understand characters they only understand numbers (binary) but it can manipulate characters internally as 0s and 1s combination. This process is known as encoding and it's reverse process is known as decoding. Here the characters are encoded in either Unicode or ASCII. Most of the time the python character are encoded in Unicode characters so we can also say that string is a collection of unicode characters.

Create Python Strings

We can create a python string by simply writing the characters within the single quotes, double quotes or triple quotes. But we mainly triple quotes for docstring or multiline string.

# defining Python Strings

str1 = 'Hello, Geeks'

print(str1)

str2 = "Hello, Geeks"

print(str2)

str3 = '''Hello, Geeks'''

print(str3)

# triple quotes string can extend multiple lines

str4 = """Hello, Geeks welcome to

                        Answersjet"""

print(str4)

Output

Hello, Geeks

Hello, Geeks

Hello, Geeks

Hello, Geeks welcome to

                        Answersjet

Accessing Characters in String

In python, we can access characters of a string in the following ways;

String Indexing

In Python, we can access the characters of a string individually with the help of indexing method. Similar to python tuple and list, the index starts from 0 which means if we have a string of 10 characters then the indexes of those characters will range from 0 to 9. We can only index integers, if we index floats or other objects then it will result into .

#Accessing string characters in Python

str = 'Answersjet'

print(str)

# first character

print(str[0])

# fifth character

print(str[4])

#  seventh character

print (str[6])

Output

Answersjet

A

e

s

Negative Indexing

Python also allows the method of negative indexing. In the negative indexing, the last character is represented by the index -1 and the second last character is represented by the index -2 and so on.

#Accessing string characters in Python

str = 'Answersjet'

print(str)

# last character

print(str[-1])

# fourth last character

print(str[-4])

#  sixth last character

print (str[-6])

Output

Answersjet

t

s

e

String Slicing

Slicing method is also used to access the characters os a string. But unlike indexing, we can access a range of characters in a string by using the slicing method. The operation of string slicing is performed by using the colon operator.

# Python String slicing program

# Creating a String

Str = "Answersjet"

print(Str)

# 3rd to 7th character

print(Str[3:7])

# characters between third and last character

print(Str[3:-1])

Output

Answersjet

wers

wersje

Deleting a String

Unlike lists, strings are immutable which means that we can't delete or modify a string after assigning it. But we can delete a string entirely by using the keyword. 

Deleting a character from python string program:

# This is simple Python program to delete characters from a String

Str = "Welcome to Answersjet"

print(Str)

# Deleting Python String character

del Str[3]

print("\nDeleting character at 3nd Index: ")

print(Str)

Here you will get an error in the output which will look something like this:

Welcome to Answersjet

Traceback (most recent call last):

File "<string>", line 5, in <module>

TypeError: 'str' object doesn't support item deletion

Deleting entire string:

# Delete entire String from python program

Str = "Welcome to Answersjet"

print(Str)

# Deleting a String by using del

del Str

print("\nDeleting entire String: ")

print(Str)

Output

Welcome to Answersjet

Deleting entire String:

Traceback (most recent call last):

File "<string>", line 7, in <module>

NameError: name 'Str' is not defined

Reassigning string

In python, strings are immutable and we can't update them after creating them but we can reassign a new string to the same old name.

Updating character of the string:

# Python Program to Update character of a String

Str = "Welcome to Answersjet"

print(Str)

# Updating a character of the String

Str[4] = 'Z'

print("\nUpdating character: ")

print(Str)

Here you will get an error in the output which will look something like this:

Welcome to Answersjet

Traceback (most recent call last):

  File "<string>", line 5, in <module>

TypeError: 'str' object does not support item assignment

Updating entire string:

# Python Program to Update entire String

Str = "Welcome to Answersjet"

print(" Old String statement: ")

print(Str)

# Updating a String

Str = "Hey, Programmers"

print("\nUpdated String statement: ")

print(Str)

Output

Old String statement: 

Welcome to Answersjet

Updated String statement:

Hey, Programmers

Formatting of String

For the formatting of python string, we use the function. The python function is a very flexible and versatile method in formatting python strings. The format string contains the Curly brackets which are treated as placeholders and then these are replaced by the method argument.

# Python format () method example

# Using Curly braces  

print("{} is best place for learning {} Tutorials".format("Answersjet","Python"))  

# Using Positional Argument  

print("{1} and {0} both are programming language ".format("Java","Python")) 

# Using Keyword Argument  

print("{x},{y},{z}".format(x = "Python", y = "C", z = "Java"))  

Output

Answersjet is best place for learning Python Tutorials

Python and Java both are programming language

Python,C,Java

Escape sequencing

Let's suppose that we want to print text- She said, "What's up?", So if we write this statement in single or double quotes then it will result into as it already contains the double quotes. 

str = "she said, "What's up?""  
print(str) 

Output

File "<string>", line 1

    str = "she said, "What's up?""
                      ^
SyntaxError: invalid syntax

So, to solve this problem python has two solution one is by using the triple quotes and other is the escape sequencing method. The escape sequence is represented by the Backslash symbol.

# Python escape sequencing example

# using triple quotes  

print('''She said, "What's up?"''')  

# using escaping single quotes  

print('She said, "What\'s up?"')  

#  using escaping double quotes  

print("She said, \"What's up?\"")  

Output

She said, "What's up?"

She said, "What's up?"

She said, "What's up?"

Following is the list of all escape sequences which are supported by the python programming language;

S.No Escape Sequence Description
1.   \newline Backslash and ignore the new line
2.        \\ Backslash
3.        \' Single Quote
4.       \\'' Double Quote
5.        \a ASCII Bell
6.        \b ASCII Backspace
7.        \f ASCII Formfeed
8.       \n ASCII Linefeed
9.        \r ASCII Carriage Return
10.        \t ASCII Horizontal tab
11.        \v ASCII Vertical tab
12.      \ooo Character with octal value ooo
13.      \xHH Character with hexadecimal value HH

Python String Methods

The following is the list of all python string methods;

S.No Method Description
1. center() Strings are padded with specified characters.
2. capitalise() The first character of string is converted into Capital letter.
3. count() To return the count of number of times a character occurs in string.
4.casefold() To return a suitable version for caseless matching.
5. expandtabs() To set the size of tab of a specified string.
6. encode() To return the encoded version of given string.
7. endswith() To check whether the string ends with given value or not.
8.format() To format a given value of the string.
9. find() To find the position of a specified value in the string.
10. formatmap() To format a given value of the string using dictionary.
11. index() To return the index of a specified character.
12.isalpha() To check whether all characters are alphabets or not.
13.isdigit() If all the characters are digit, it returns true.
14. isalnum() To check whether all characters are alphanumeric or not.
15. isdecimal() If all the characters are decimal, it returns true.
16. islower() If all the characters are in lowercase, it returns true.
17.isprintable() To check whether all the characters are printable or not.
18. isidentifier() If the specified string is an identifier, then it returns true.
19. istitle() To check whether the given string is Titlecased or not.
20. isascii() If all the characters of string are ASCII characters, it returns true.
21.isnumeric() To check the numeric characters of a string.
22. isupper() If all the characters are in uppercase, it returns true.
23. isspace() To check the whitespace characters of a string.
24. ljust() To return a left-justified version of a string.
25.lower() To return a lowercased string.
26.join() To convert the items of an iterable into a string.
27. maketrans() To return a translation table.
28. partition() Where the string is parted into three parts, it returns a tuple.
29. lstrip() To return a left-trimmed version of a string.
30.rfind() To return the highest index of character of a string.
31. rjust() To return the right-justified string.
32. replace() To replace one specified value with other specified value of a string.
33. rindex() To return the highest index of character of a string.
34.rstrip() To return the right-trimmed string.
35. splitlines() Return a list and at line breaks splits the string.
36. rpartition() To return a tuple.
37. rsplit() To return a list and split the string at specified separator.
38.split() To return a list and split the string at specified separator.
39.strip() To return a trimmed string.
40. title() To return a Titlecased version of a string.
41. startswith() If the string starts with specified string it returns true.
42. swapcase() To swap cases, upper case becomes lower case and vice-versa.
43.translate() To return a translated version of string.
44. zfill() The copy of a string padded with zeros is returned.
45. upper() To convert a string into uppercased string.

Conclusion

Above we have learnt about python strings, how to create python strings, access characters in string, string slicing, deleting/updating a string, formatting of strings and escape sequencing. Strings are the collection or sequence of characters which are written within the single quotes, double quotes or triple quotes.