Strings in Python

Python Strings

Definition:- String is a sequence of characters or array of character.


Initialization of strings in Python

Characters are placed in single or double quotation marks, for the initialization of string in Python.


Program

>>> a = "Hello world!"
>>> print(a)
Hello world!
>>> b = 'Hello world!'
>>> print(a)
Hello world!


Accessing characters of a string

As strings are array of characters, so the elements of string can be accessed by using index numbers.

  • Indexing starts with 0.
    • First character has an index number of 0, second character has an index number of 1 and soo on.

Accessing an element in a string

Use index to access an element in a string. 

Program 

>>> st = "This is how you can access"
>>> st[0]
'T'
>>> st[9]
'o'



String slicing 

Provide start index and stop index to slice a string. 


Syntax / format:-

string_name[start index : stop index] 


Start index:- start the slicing from. 


Stop index:- Till where to slice. 

Program 

>>> st = "This is how you can access"
>>> st[8:16]
'how you '


Slicing starts from the beginning if start index is not specified.

Program


>>> st = "This is how you can access"
>>> st[:19]
'This is how you can'


If end index is not specified then string will slice till the end.

Program


>>> st = "This is how you can access"
>>> st[16:]
'can access'


When both start index and end index is not specified then the whole string is returned.

Program

>>> st = "This is how you can access"
>>> st[:]
'This is how you can access'

String slicing with intervals

Slice the string by taking specified steps.


Syntax / format:-

string_name[start index : stop index]

 

Program


>>> st = "This is how you can access"
>>> st[8:16:2]
'hwyu'


Steps taken in string by not specifying start index and end index.

Program


>>> st[::3]
'Tssoy ncs'



Length of string 

Python built-in function len(), returns the number of characters in a string. 

Program 


>>> le = "HoW long I'm"
>>> len(le)
12



String concatenation

Make use of '+' operator for joining of strings. 

Program 


>>> a = "Hello "
>>> b = "world!"
>>> c = a + b
>>> print(c)
Hello world!


Concatenation with more strings.

Program


>>> a = "Hello "
>>> b = "world"
>>> e = "!"
>>> c = a + b + e
>>> print(c)
Hello world!



Strings are immutable

String does not support item assignment.

Program


>>> a = "Hello world"
>>> a[0] = "c"
Traceback (most recent call last):
  File "<pyshell#77>", line 1, in <module>
    a[0] = "c"
TypeError: 'str' object does not support item assignment
>>>



String placeholders

String formatting can be done in 2 ways. 

  1. Using '%' operator. 
  2. Using format() method 

String formatting using  modulus operator

Placeholders are placed in the string and the value to be passed into it is defined outside the string.

Program


>>> "Take $%d from John" %30
'Take $30 from John'


String formatting with more placeholders.

Program


>>> "Take $%d form %s" %(30, 'John')
'Take $30 form John'


For different data types there are different place holders.


For string it's '%s', for integers it's '%d' , for floating point numbers it's '%f' and some more...


PlaceholdersMeaning
%dInteger
%iInteger
%uInteger
%fFloat
%FFloat
%oOctave
%xHexadecimal
small letters
%XHexadecimal
capital letters
%cCharacter, if passed integer then
it's corresponding ASCII value is
returned
%sString
%rString placed with single quotation
marks
%eExponential
small 'e'
%EExponential
capital 'E'
%gSame as 'e' but, exponent notation is
shown when exponential value is  
less than -4 or greater than 5
%GSame as 'E' but, exponent notation is
shown when exponential value is  
less than -4 or greater than 5

String formatting using format() method

Curly braces are used as placeholders, and the value to placed in that placeholders are passed as argument to the format() method.

Program


>>> "Take ${} form John".format(35)
'Take $35 form John'


String formatting with more placeholders.

Program


>>> "Take ${} from {}".format(35, "John")
'Take $35 from John'


It's easy to control the placing of values on to the placeholders, by providing the index of the value that is been passed as argument to the format() method.

Program


>>> "From {1} take ${0}".format(35, "John")
'From John take $35'


One argument value can be placed more number of times in placeholders, with string formatting with format() method.

Program


>>> "Take ${0} from this {1} not that {1}".format(35, "John")
'Take $35 from this John not that John'



In operator in string

The in operator check if a character or word or phrase is present in the string.

Program


>>> st = "Is there something in it"
>>> 'i' in st
True
>>> 'something' in st
True
>>> 'anything' in st
False
>>> 'z' in st
False



String comparison

Check if two strings are equal.


Returns 'True' if two strings are equal, and 'False' if they are not equal.

Program


>>> a = "Hello"
>>> b = "Hey"
>>> c = "Hello"
>>> a == a
True
>>> a == c
True
>>> a == b
False
>>> c == b
False



All string methods

Here are all the built-in methods available with string.


MethodsMeaning
capitalize()Makes the first character upper case
casefold()Converts string to lower case
center()Return a centered string
count()Total number of occurrences of 
substring in string
encode()Encodes the string
endswith()Returns True if string ends with the
specified substring
expandtabs()Resize the tab
find()Returns lowest index of substring in
a string
format()Return formatted version of the
string using args and kwargs
format_map()Returns formatted version of string
using mapping
index()Returns the lowest index of substring
in a string
isalnum()Returns True if all the characters 
are numbers (0-9)
isalpha()Returns True if all the characters are 
alphabet (a-z) and (A-Z)
isascii()Returns True if all the characters in 
string are ASCII,
isdecimal()Returns True if all the characters are
decimals (Unicode)
isdigit()Returns True if all the characters 
are digits
isidentifier()Returns True if the string is valid
Python identifier
islower()Returns True if all the characters in a
string are lower case
isnumeric()Returns True if all the characters are
numbers.
isprintable()Returns True if all the characters in a
string are printable
isspace()Returns True if full string is
whitespace, no other char...
istitle()Returns True if  first letter of each
 word in a string is upper case.
isupper()Returns True if all the characters
in a string are upper cased
join()Joins the values specified in iterable
with a string specified as separator
ljust()Align the string at left by adding
characters at the right
lower()Converts all the alphabets to lower
case letters
lstrip()Removes the leading whitespace
maketrans()Modifies the characters of a string,
by replacing or removing
partition()Finds specified separator and return
3-tuple
1.   String before separator
2.   Separator
3.   String after separator
removeprefix()Removes the characters specified if 
it is at the beginning of a string
removesuffix()Removes the characters specified if 
it is present at the end of the string
replace()Old substring replaced by new
rfind()Find the index of substring
occurring at the last 
Returns -1 on failure
rindex()Find the index of substring
occurring at the last 
Raises ValueError on failure
rjust()Align the string at right by adding
characters at the left
rpartition()Finds last specified separator and
return 3-tuple
1.    String before separator
2.    last Separator
3.    String after separator
rsplit()Returns a list in which each element
is a word of a string, and the
words are separated by the characters
specified
rstrip()Removes the specified characters from
the end of the string
split()same as rsplit, but in rsplit we can
specify the maximum number of 
splits but, in this method we can't
splitlines()Returns a list of strings, splitting is
done with line breaks '\n'(new line).
startswith()Returns Ture if string starts with the
specified characters
strip()Removes all specified characters from 
the string
swapcase()Converts uppercase to lowercase and 
lowercase to uppercase
title()Returns a string in which first letter of 
each word is uppercased
translate()Replace each character in a string by
the specified mapping table
upper()Converts all the characters to upper
case
zfill()Adds '0' at the beginning of the string
with specified width




Conclusion

String is sequence of characters or array of character.

Sentences are placed in single or double quotation marks, for the creation of a string.

Here we learned initialization of a string, accessing characters, accessing string in a range, string slicing, string formatting and the methods available with the string. 





Previous                          Next

If you have any query, feel free to ask.

Post a Comment

If you have any query, feel free to ask.

Post a Comment (0)