AppDividend
Latest Code Tutorials

Python Strings Example | String In Python Tutorial

0

Python Strings Example | String In Python Tutorial is today’s topic. In Python, Strings are the arrays of bytes representing the Unicode characters. Python does not have the character data type, and a single character is simply a string with a length of 1.

#What is String in Python

A string is the sequence of characters.

A character is simply the symbol. For example, an English language has 26 characters.

Computers do not deal with characters, and they deal with binary numbers. Even though you may see the characters on your screen, internally, it is stored and manipulated as the combination of 0’s and 1’s.

The conversion of character to the number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the simplified encoding used.

You can count the characters in one string using the Python len() function.

Python Strings Example

In Python, the string is the sequence of the Unicode character.

Unicode was introduced to include every character in all the languages and bring uniformity in encoding.

Like many other programming languages, strings in Python are the arrays of bytes representing Unicode characters.

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

Square brackets can be used to access the items of a string.

#How to create a string in Python

Python Strings can be created using the single quotes or double quotes or even the triple quotes.

String in the single quotes cannot hold any other single-quoted character in it; otherwise, an error arises because a compiler won’t be able to recognize where to start and end the string.

If we want to overcome this error, the use of double quotes is preferred, because it helps in the creation of Strings with a single quotes in them.

For strings which contain the Double quoted words in them, use of triple quotes is suggested. Along with this, triple quotes also allow a creation of multiline strings.

See the following examples of String literals.

print("Millie Bobby Brown")
print('Millie Bobby Brown')
print('''Millie Bobby Brown''')

We can use single and double quote.

➜  pyt python3 app.py
Millie Bobby Brown
Millie Bobby Brown
Millie Bobby Brown
➜  pyt

We can display the string literal with the print() function.

In the above example, we have used single, double, and triple quotes. We will get the same output, but the triple quote is useful when we have Double quoted words as a string. See the following code.

print('''Mill's ''')

See the following output.

➜  pyt python3 app.py
Mill's
➜  pyt

#Multiline Strings

You can assign a multiline string to a variable by using three quotes. See the following code.

muldata = """Eleven's character Played
by Millie Bobby Brown is the 
best thing that ever happened in the
Drama Series."""
print(muldata)

See the following output.

➜  pyt python3 app.py
Eleven's character Played
by Millie Bobby Brown is the
best thing that ever happened in the
Drama Series.
➜  pyt

#Accessing characters in Python

We can access the characters of Python using index just like arrays in Programming languages.

In Python, individual characters of the String can be accessed by using a method of Indexing, to access the range of characters in the String, method of slicing is used.

Slicing in the String is done by using the Slicing operator (colon). Indexing allows negative address references to access the characters from the back of a String, e.g., -1 refers to a last character, -2 refers to a second last character and so on.

While accessing the index out of the range will cause the IndexError. Only Integer datatypes are allowed to be passed as the index, float, or other types will cause a TypeError.

See the following code example.

# app.py

StrA = "MillieBobbyBrown"
print("Initial String: ", StrA)
print("\nFirst character of String is: ", StrA[0])
print("\nLast character of String is: ", StrA[-1])
print("\nSlicing characters from 3-12: ", StrA[3:12])
print("\nSlicing characters between " + "3rd and 2nd last character: ", StrA[0:-5])

See the following output.

➜  pyt python3 app.py
Initial String:  MillieBobbyBrown

First character of String is:  M

Last character of String is:  n

Slicing characters from 3-12:  lieBobbyB

Slicing characters between 3rd and 2nd last character:  MillieBobby
➜  pyt

#Deleting/Updating from a String

In Python, Updation or deletion of the characters from the string is not allowed. It will cause an error because item assignment or item deletion from the String is not supported.

Although deletion of the entire String is possible with the use of the built-in del keyword, it is because Strings are immutable, hence elements of the String cannot be changed once it has been assigned.

Only new strings can be reassigned to that same name.

Now, let’s try to update the string, although we know that we will get some error.

See the following code example.

# app.py

StrA = "MillieBobbyBrown"
print("Initial String: ") 
print(StrA)

StrA[2] = 'K'
print("\nUpdating character at 2nd Index: ") 
print(StrA)

Okay, so we are trying to modify the StrA. Now, see the following output.

➜  pyt python3 app.py
Initial String:
MillieBobbyBrown
Traceback (most recent call last):
  File "app.py", line 5, in <module>
    StrA[2] = 'p'
TypeError: 'str' object does not support item assignment

Now, delete the string using the del keyword.

# app.py

StrA = "MillieBobbyBrown"
print("Initial String: ") 
print(StrA)

del StrA
print(StrA)

See the following output.

➜  pyt python3 app.py
Initial String:
MillieBobbyBrown
Traceback (most recent call last):
  File "app.py", line 6, in <module>
    print(StrA)
NameError: name 'StrA' is not defined
➜  pyt

See, after we have removed the StrA, it is now saying that StrA is not defined.

#Formatting of Strings

We can format the string using the Python String format() method.

Python String format() method takes any number of arguments. But, it is mainly divided into the two types of parameters which are following.

  1. Positional parameters – It is a list of parameters that can be accessed with an index of a parameter inside the curly braces {index}.
  2. Keyword parameters – It is a list of the parameters of type key=value that can be accessed with the key of a parameter inside curly braces {key}.

See the following example.

# app.py

name = 'Millie'
coins = 15
print('Hello {}, you are {} years old.'.format(name, coins))

See the following output.

name = 'Millie'
coins = 15
print('Hello {}, you are {} years old.'.format(name, coins))

Python String strip() method removes any whitespace from the beginning of the end.

See the following code example.

name = "      Millie   "
print(name.strip())

See the following output.

➜  pyt python3 app.py
Millie
➜  pyt

Finally, Python Strings Example | String In Python Tutorial is over.

Leave A Reply

Your email address will not be published.

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