in , ,

Python Strings

Python Strings

Python Strings: In this tutorial, you will learn how to make, formate, modify, and erase strings in Python. Also, you will be acquainted with different string operations and functions.

What is String in Python?

A string is a sequence of characters.

A character is just an image. For instance, the English language has 26 characters.

Computers don’t deal with characters, they manage numbers (twofold). Despite the fact that you may see characters on your screen, inside it is put away and controlled as a blend of 0s and 1s.

This change of character to a number is called encoding, and the converse procedure is translating. ASCII and Unicode are a portion of the popular encodings used.

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. You can learn about Unicode from Python Unicode.


How to create a string in Python?

Strings can be made by encasing characters inside a solitary statement or twofold statements. Indeed, even triple statements can be used in Python however for the most part used to represent to multiline strings and docstrings.

# defining strings in Python
# all of the following are equivalent
my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)

my_string = '''Hello'''
print(my_string)

# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
           the world of Python"""
print(my_string)

When you run the program, the output will be:

Hello
Hello
Hello
Hello, welcome to
           the world of Python

How to access characters in a string?

We can access individual characters using indexing and scope of characters using slicing. The file begins from 0. Attempting to get to a character out of record range will raise an IndexError. The list must be a whole number. We can’t use drifts or different sorts, this will result in TypeError.

Python allows negative indexing for its sequences.

The index of – 1 refers to the last thing, – 2 to the second keep going thing, etc. We can get to a scope of things in a string by using the slicing operator :(colon).

#Accessing string characters in Python
str = 'worldofitech'
print('str = ', str)

#first character
print('str[0] = ', str[0])

#last character
print('str[-1] = ', str[-1])

#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])

#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
When we run the above program, we get the following output:
str = worldofitech
str[0] =  w
str[-1] =  h
str[1:5] =  orl
str[5:-2] =  do

 If we try to access an index out of the range or use numbers other than an integer, 
we will get errors. 
# index must be in range
>>> my_string[15]  
...
IndexError: string index out of range

# index must be an integer
>>> my_string[1.5] 
...
TypeError: string indices must be integers

How to change or delete a string?

Strings are immutable. This means that elements of a string cannot be changed once they have been assigned. We can simply reassign different strings to the same name.

>>> my_string = 'worldofitech'
>>> my_string[5] = 'a'
...
TypeError: 'str' object does not support item assignment
>>> my_string = 'Python'
>>> my_string
'Python'

We cannot delete or remove characters from a string. But deleting the string entirely is possible using the del keyword.

>>> del my_string[1]
...
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>> my_string
...
NameError: name 'my_string' is not defined

Python String Operations

There are many operators that can be performed with the string which makes it one of the most utilized information types in Python.

To learn more about the data types available in Python visit: Python Data Types

Connection of Two or More Strings

Joining two or more strings into a single one is called connection.

The + operator does this in Python. Essentially composing two string literals together additionally links them.

The * operator can be used to rehash the string for a given number of times.

# Python String Operations
str1 = 'Hello'
str2 ='World!'

# using +
print('str1 + str2 = ', str1 + str2)

# using *
print('str1 * 3 =', str1 * 3)

When we run the above program, we get the following output:

str1 + str2 =  HelloWorld!
str1 * 3 = HelloHelloHello

Writing two string literals together also concatenates them like + operator.

If we want to concatenate strings in different lines, we can use parentheses.

>>> # two string literals together
>>> 'Hello ''World!'
'Hello World!'

>>> # using parentheses
>>> s = ('Hello '
...      'World')
>>> s
'Hello World'

Iterating Through a string

We can iterate through a string using a for a loop. Here is an example to count the number of ‘l’s in a string.

# Iterating through a string
count = 0
for letter in 'Hello World':
    if(letter == 'l'):
        count += 1
print(count,'letters found')

When we run the above program, we get the following output:

3 letters found

String Membership Test

We can test if a substring exists within a string or not, using the keyword in.

>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False

Built-in functions to Work with Python

Different implicit capacities that work with sequence work with strings also.

Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for iteration.

Similarly, len() returns the length (number of characters) of the string.

str = 'cold'

# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)

#character count
print('len(str) = ', len(str))

When we run the above program, we get the following output:

list(enumerate(str) =  [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')]
len(str) =  4

Python String Formatting

Escape Sequence
If we want to print a text like He said, “What’s there?”, we can neither use single quotes nor double-quotes. This will result in a SyntaxError as the text itself contains both single and double-quotes.

>>> print("He said, "What's there?"")
...
SyntaxError: invalid syntax
>>> print('He said, "What's there?"')
...
SyntaxError: invalid syntax

One way to get around this issue is to use triple quotes. Alternatively, we can use escape sequences.

An escape sequence begins with an oblique punctuation line and is deciphered in an unexpected way. In the event that we utilize a solitary statement to speak to a string, all the single statements inside the string must be gotten away. Comparable is the situation with twofold statements. Here is the manner by which it tends to be done to represent the above text.

# using triple quotes
print('''He said, "What's there?"''')

# escaping single quotes
print('He said, "What\'s there?"')

# escaping double quotes
print("He said, \"What's there?\"")

When we run the above program, we get the following output:

He said, "What's there?"
He said, "What's there?"
He said, "What's there?"

Here is a list of all the escape sequences supported by Python.

Escape SequenceDescription
\newlineBackslash and newline ignored
\\Backslash
\’Single quote
\”Double quote
\aASCII Bell
\bASCII Backspace
\fASCII Formfeed
\nASCII Linefeed
\rASCII Carriage Return
\tASCII Horizontal Tab
\vASCII Vertical Tab
\oooCharacter with octal value ooo
\xHHCharacter with hexadecimal value HH

Here are some examples

>>> print("C:\\Python32\\Lib")
C:\Python32\Lib

>>> print("This is printed\nin two lines")
This is printed
in two lines

>>> print("This is \x48\x45\x58 representation")
This is HEX representation

Raw String to ignore escape sequence

Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place  r or R before the string. This will suggest that it is a crude string and any departure arrangement inside it will be ignored.

>>> print("This is \x61 \ngood example")
This is a
good example
>>> print(r"This is \x61 \ngood example")
This is \x61 \ngood example

The format() Method for Formatting Strings

The format() method that is available with the string object is very versatile and powerful in formatting strings. Format strings contain curly braces {} as placeholders or replacement fields that get replaced.

We can use positional arguments or keyword arguments to specify the order.

# Python string format() method

# default(implicit) order
default_order = "{}, {} and {}".format('salman','khan','worldofitech')
print('\n--- Default Order ---')
print(default_order)

# order using positional argument
positional_order = "{1}, {0} and {2}".format('salman','khan','worldofitech')
print('\n--- Positional Order ---')
print(positional_order)

# order using keyword argument
keyword_order = "{s}, {k} and {w}".format(s='salman',k='khan',w='worldofitech')
print('\n--- Keyword Order ---')
print(keyword_order)

When we run the above program, we get the following output:

--- Default Order ---
salman, khan and worldofitech

--- Positional Order ---
khan, salman and worldofitech

--- Keyword Order ---
worldofitech, khan and salman

The format() method can have optional format specifications. They are separated from the field name using the colon. For example, we can left-justify <, right-justify > or center ^ a string in the given space.

We can also format integers as binary, hexadecimal, etc. and floats can be rounded or displayed in the exponent format. There are tons of formatting you can use.

>>> # formatting integers
>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'

>>> # formatting floats
>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'

>>> # round off
>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'

>>> # string alignment
>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','cake')
'|butter    |  bread   |       cake|'

Old style formatting

We can even format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this.

>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

Common Python String Methods

There are numerous methods available with the string object. The format() method that we mentioned above is one of them. Some of the commonly used methods are lower(), upper(), join(), split(), find(), replace() etc.

>>> "woRlDoFiTeCh".lower()
'worldofitech'
>>> "woRlRdofItecH".upper()
'WORLDOFITECH'
>>> "This will split all words into a list".split()
['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
'This will join all words into a string'
>>> 'Happy New Year'.find('ew')
7
>>> 'Happy New Year'.replace('Happy','Brilliant')
'Brilliant New Year'

Please feel free to give your comment if you face any difficulty here.

For More Latest Articles Click on Below Link.

salman khan

Written by worldofitech

Leave a Reply

python tuple

Python Tuple

python sets

Python Sets