Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 862

Strings in Python With Method Examples

$
0
0

String which represents a sequence of characters is one of the most used type in most of the applications. So programming languages generally ensure that String is well optimized and has an extensive API with methods to cover most of the String operations. Python is no different and String in Python has also many optimization features and lots of methods.

Python String

String in Python is of type “str” which means every String literal created is an object of str class. strings in Python are arrays of bytes representing unicode characters.

For characters there is no separate data type in Python, a single character is also string of length 1.


Creating a String in Python

You can create a String in Python by enclosing a group of characters in either single quotes or double quotes.

Both of the following are valid and work in the similar way-


s = 'Hello'

s = "Hello"

You can also create String in Python using tripe single quotes or triple double quotes. This way of creating String is useful if you have a multiline String.


s = '''This tutorial on String in Python gives examples of
creating strings, string optimizatin features and examples
of functions in String.'''

print(s)

Output


This tutorial on String in Python gives examples of
creating strings, string optimizatin features and examples
of functions in String.

If you have to show quotes as part of string then you can use another type of quote to enclose string and the quote which has to be part of string in the inner string.

For example if you have to show text – This isn’t part of the original deal
then use double quotes to enclose the String and single quote as part of the text.


s = "This isn't part of the deal"
print(s)

Output


This isn't part of the deal

If you have to show text- He said “May I come in”
then use single quotes to enclose the String and double quotes as part of the text.


s = 'He said "May I come in"'
print(s)

Output


He said "May I come in"

Escape characters in a String

You can also use escape characters with a String in Python.

Some of the escape characters that can be used in Strings are-

Escape characterDescription
\aBell or alert
\bBackspace
\nNew line
\rCarriage return (enter)
\sSpace
\tHorizontal tab space
\vVertical tab space

For example-


s = "This text has \t spaces and goes to \n next line"
print(s)

Output


This text has spaces and goes to
next line

Backslash (\) is also used as an escape sequence in Python. If you want double or single quote with in a String then you can also put a backslash followed by a quote (\" or \').


s = "He said \"this looks good\" to his colleague"
print(s)

Output


He said "this looks good" to his colleague

Since backslash is used as an escape sequence so you’d need two backslashes (\\) if you have to display backslash as part of String. One for displaying and another as escape sequence.


print("C:\\Python\\")
print(s)

Output


C:\Python\

Accessing characters in String (String indexing)

Since String in Python is stored as an array so array indexing can be used to access characters of a String. Index is 0 based so first character is at index 0, second is at index 1 and so on.

In Python you can also use negative indexing. When negative number is used as index String is accessed backward so -1 refers to the last character, -2 second last and so on.

String in Python

Example to access characters of a String


s = "Hello World"
#first character
print(s[0])
#last character
print(s[10])
#last character
print(s[-1])
#first character
print(s[-11])

Output


H
d
d
H

Trying to use an index which is out of range results in IndexError. Using any other type except integer as index results in TypeError.


s = "Hello World"
#index out of range
print(s[12])

Output


print(s[12])
IndexError: string index out of range

If you want to access a part of a String then you use slicing operator. Slicing is done using “[:]” operator.

For example if you want to access characters between index 3 and 7.


s = "Hello World"
#slicing String
print(s[3:7])

Output


lo W

Strings in Python are immutable

String in Python is immutable which means content of String object can’t be modified once assigned.

Trying to modify a String by updating or deleting any character results in error as Strings are immutable.

Updating String


s = "Hello World"
#changing String
s[3] = 't'

Output


s[3] = 't'
TypeError: 'str' object does not support item assignment

Deleting character in a String


s = "Hello World"
#deleting char
del s[3]

Output


del s[3]
TypeError: 'str' object doesn't support item deletion

Note that for immutable object though content can’t be changed but the reference can be changed. So a string object can be made to reference a new String.


s = "Hello World"
print(id(s))
s = "Hi"
print(s)
print(id(s))

Output


2976589114032
Hi
2976587746472

id function in CPython implementation returns the address of the object in memory. As you can see s starts referencing to the new memory location when a new String is assigned.

String interning in Python

String interning means that two string objects that have the same value share the same memory. If you have one string object with some value and you create second string object with the same value then the second string object shares the reference with the first string object. By interning strings memory is saved.

String interning is possible in Python as Strings are immutable so content can't be changed.


s1 = "Hello"
s2 = "Hello"
print(s1 is s2)
print(id(s1))
print(id(s2))

Output


True
1347382642256
1347382642256

In the example two string objects are created having the same value. As you can see when is operator is used to check whether both the operands refer to the same object or not true is returned.

Also id() function returns the same memory address for both the objects.

Operators used with String

Following operators are used with String in Python-

1. + operator-‘+’ operator when used with Strings in Python acts as a concatenation operator . It is used to append one string at the end of another string.


s1 = "Hello"
s2 = " World"
print(s1 + s2)

Output


Hello World

2. * operator- * operator is the repetition operator and used to repeat the string for the given number of times.


s1 = '*'
for i in range (1, 5):
print(s1*i)

Output


*
**
***
****

3. in and not in operators- These operators are used for checking whether the given string or character is part of another String.

4. Slice operator- Slice operator ([:]) is used to access a substring with in a string.

That's all for this topic Strings in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Operator Overloading in Python
  2. Passing Object of The Class as Parameter in Python
  3. self in Python
  4. Magic Methods in Python With Examples
  5. Nonlocal Keyword in Python With Examples

You may also like -

  1. Name Mangling in Python
  2. instanceof Operator in Java
  3. Java Exception Handling Tutorial
  4. Difference Between ArrayList And LinkedList in Java
  5. Semaphore in Java Concurrency
  6. Checking Number Prime or Not Java Program
  7. Spring Setter Based Dependency Injection
  8. Transaction Management in Spring

Viewing all articles
Browse latest Browse all 862

Trending Articles