Python Strings Tutorial 100 %

Python Strings

strings in python
Python Strings


Python strings are stored as individual characters in contiguous locations, with two-way index for each location. Consider following figure :

Structure of a Python String
Structure of a Python String.

Form Fig. 2.1 you can infer that :

  • Python strings are stored by storing each character separately in contiguous locations.
  • The characters of the strings are given two-way indices :
    0, 1, 2, … size-1 in the forward direction and
    -1, -2, -3, … -size in the backward direction.

Thus, you can access any character as [] e.g., to access the first character of string name shown in Fig. 2.1, you’ll write name[0], because the index of first character is 0. You may also write name[-6] for the above example i.e., when string name is storing “PYTHON”.


Length of string variable can be determined using function len(), i.e., to determine length of above shown name, you may write :


len(name)

which will give you 6, indicating that string name stores six characters.

1. Item Assignment not Supported


One important thing Python strings is that you cannot change the individual letters of a string by assignment because strings are immutable and hence item assignment is not supported, i.e.,

name = 'hello'
name[0] = 'p'

will cause an error like :

Trackback (most recent call last) :
File "<pyshell#3>", line 1, in <module>
    name[0] = 'p'
TypeError : 'str' object does not support item assignment

2. Traversing a String


Traversing refers to iterating through the elements of a string, one character at a time.
To traverse through a string, you can write a loop like :

code = "Powerful"
for ch in in code :
      print(ch, '~', end = ' ')

The above code will print :

P ~ o ~ w ~ e ~ r ~ f ~ u ~ l ~

Note :


Traversing refers to iterating through the elements of a string, one character at a time.

3. String Operators


In this section, you’ll be learning to work with various operators that can be used to manipulation strings in multiple ways.

3.1 String Concatenation Operator +


The + operator creates a new string by joining the two operand strings, e.g.,

"power" + "ful"
will result into
'powerful'

Caution !


The + operator has to have both operands of the same type either of number types (for addition) or of string types(for multiplication). IIt cannot work with one operand string and one as number.

python string concatenation

3.2 String Replication Operator *


The use a * operator with strings, you need two types of operands – a string and a number, i.e., as number operand tells the number of times, it is to be repeated; Python will create a new string that is a number of repetitions of the string operand.


For example,
3 * "Ha!"

will return

'Ha!Ha!Ha!'

Caution !


The * operator has to either have both operands of the number types(for multiplication) or one string type and one number type (for replication). It cannot work with both operands of string types.

3.3 Membership Operators


There are two membership operators for strings(in fact, for all sequence types). These are in and not in.


in :-

returns True if a character or a substring exists or a substring exists in given string ; False otherwise


not in :-

returns True if a character or a substring does not exist in given string; False otherwise


Both membership operators(when used with strings), require that both operands used with them are of string type, i.e.,

<string> in <string>
<string> not in <string>

Now, let’s have a look at some examples :

>>> "a" in "heya"
True
>>> "jap" in "heya"
False
>>> "jap" in "Japan"
False
>>> sub = "help"
False
>>> sub2 not in string
True
>>> string = "helping hand"
>>> sub2 = 'HELP'
>>> sub in string
True
>>> sub2 in string
False
>>> sub not in string
False

3.4 Comparison Operator


Python’s standard comparison operators i.e., all relational operators(<, <=, >, >=, ==, !=,) apply to strings also. The comparisons using these operators are based on the standard character-by-character comparison rules for ASCII or Unicode(i.e., dictionary order). Thus, you can make out that :

“a” == “a”
will give True


“abc” == “abc”
will give True

“a” ! = “abc”
will give True


“A” != “a”
will give True


“ABC” == “abc”
will give False (letter’ case is different)


“abc” != “Abc”
will give False (letter’ case is different)

String comparison principles are :

  • Strings are compared on the basis of lexicographical ordering (ordering in dictionary).
  • Upper-case letters are considered smaller than the lower-case letters.

Determining ASCII/Unicode value of a String Character


Python offers a built-in function ord( ) that takes a single character and returns the corresponding ASCII value or Unicode value :

ord(<single-character>)      #returns ASCII value of passed character

The opposite of ord( ) function is chr( ), i.e., while ord( ) returns ASCII value of a character, the chr( ) takes the ASCII value in integer form and returns the character corresponding to that ASCII value.


The general syntax of chr( ) function is :

chr(<int>)                 #Gives character corresponding to passed ASCII
                                  #value given as integer
Consider these examples :
>>> ord('A')
65
>>> ord(u'A')
65
>>> chr(65)
'A'
>>> chr(97)
'a'

4. String Slices


The term ‘string slice’ refers to a part of the string, where strings are sliced using a range of indices. That is, for a string say name, if we give name[n:m] where n and m are integers and legal indices, Python will return a slice of the string by returning the characters falling between indices n and m :
starting at n, n+1, n+2 … till m-1.

Following fugure shows some string slices using the string :

Interesting Inference

String Slicing in Python
String Slicing in Python : Python Strings


Using the same string slicing technique, you will find that

  • for any index n, s[:n] + s[n:] will gave you original string s.

This works even for n negative or out of bounds.
Consider the string namely word storing ‘amazing’.

>>> word[3:], word[:3]
'zing' 'ama'
>>> word[:3] + word[3:]
'amazing'
>>> word[:-7], word[-7:]
' ' 'amazing'
>>> word[:-7] + word[-7:]
'amazing'
  • Index out of bounds causes error with but slicing a string outside the bounds does not cause error.
s = "Hello"
print(s[5])

Will cause error because 5 is invalid index-out of bounds. for string “Hello”


But if you give

s = "Hello"
print(s[4:8])

One limit is outside the bounds (length of Hello is 5 and thus valid indexes are 0-4)

print(s[5:10])

Both limits are outside the bounds

Note :

  1. For any index n, s[:n] + s[n:] will give you original string s.
  2. string [:: -1] is an easy way to reverse a string.

Python Strings video :

Python Strings video credit : edureka

Python Strings

Frequently Asked Questions : python strings

Q 1. What are strings in Python?

string in Python is a sequence of characters. It is a derived data type. Strings are immutable. This means that once defined, they cannot be changed. Many Python methods, such as replace() , join() , or split() modify strings.
Python Strings Tutorial

Q 2. What is string in python with example?

string is a sequence of characters. A character is simply a symbol. For example, the English language has 26 characters. … In Python, a string is a sequence of Unicode characters. Unicode was introduced to include every character in all languages and bring uniformity in encoding.
Python Strings Tutorial

Q 3. How do you define a string in Python 3?

Working with Strings in Python 3

string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. Made up of Unicode, strings are immutable sequences, meaning they are unchanging.
Python Strings Tutorial

Q 4. How do you call a string in Python?

To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable. You can look into how variables work in Python in the Python variables tutorial. For example, you can assign a character ‘a’ to a variable single_quote_character .
Python Strings Tutorial

Q 5. Is string function in Python?

Python string encode() function is used to encode the string using the provided encoding. Python String count() function returns the number of occurrences of a substring in the given string. … Python string endswith() function returns True if the string ends with the given suffix, otherwise it returns False.
Python Strings Tutorial

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *