DEV Community

Cover image for Mastering Strings - Python
Sakshi
Sakshi

Posted on

Mastering Strings - Python

Good day guys,

Python Unleash'd 05

Image description

I always wished someone taught me strings along with all its methods and behaviors, there are some exceptions where things become complex. Lets see all applicable methods on strings one by one.

Here we see empty string with nothing, empty string with space

print("first")
empty_string = ""
print(empty_string, len(empty_string))
print("second")
string_with_space = " "
print(string_with_space, len(string_with_space))
print("third")
Enter fullscreen mode Exit fullscreen mode

And the output is :

Image description

String with one space has length 1 while without space has 0 length, i.e, an empty string.

Lets move forward to see different ways of creating string
str = 'string'
str = "string"

''' str
    =
    multiline
    string 
'''
Enter fullscreen mode Exit fullscreen mode

The output of multiline string with triple quotes :

Image description

Image description

Random Access

We can access string character using negative and positive indexing. Positive indexing means from left to right, while negative starts from back to front. -1 index means last element.

Slicing (was once a toughest concept for me)

  • Colon is used for slicing.
  • Slicing, as the name suggests, means cutting string in slices
  • Slicing does not change string content unless we assign it to sliced string

Image description

TO GET SUBSTRING YOU SLICE THE STRING

Now let us see how index is given within these square brackets, by breaking it in pieces.

So last index is always excluded in the range.
When I write string[0:3]
0 is the starting index, while 2 is the end index. It excludes last index.

In string[1:-1], it includes char from 1 to -2 and not from 0 to -1.

Please note that indexing starts from 0 and not 1

So is not there any way to get entire string as substring

I call slice as substring. Yes, there is a way.

string[0:]

Now we'll get entire string.

Reverse string with help of colons

string[::-1]

Here we are introduced to a new param, third digit after second colon. It is used for step.

We are taking some easy examples here, to understand this STEP.

Look at the following examples, consider there is a string 'temp = maple_string' as its value.

  • temp[:] gives entire string
  • tem[0:] gives entire string
  • temp[:1] gives only first character
  • temp[::] gives empty string

first param before first column is for start index
second param after first colon is for end index
leaving blank means, start or end depending on colon

If there is mistake, or you write end index before start index, then you get empty string returned.

Image description

string[1:0] returns empty string

temp[-1:] is same as temp[-1], both return last char

temp[:1] is same as temp[0], in the former, 1 is not included as it is end index so only 0th char is returned.

Image description

Consider, temp = "maple_string" and
temp[1:2:1]

last part of slice can not be 0, in three step, either remove third step or it should not be zero. IT CAN BE ANY POSITIVE OR NEGATIVE NUMBER BUT NOT ZERO.

Image description

In above code snapshot, we see there -55 as the STEP, which does not even exist, so when it takes -55th step between start and end index, it does not get anything so it returns empty string, not even space.

Below we have another code snapshot from notebook, here I have provided valid STEP size, which will not return empty string.

Image description

It obtains the substring from index one to one only, and step size is one so it returns just that character which is at temp[1]

Step size of one does not mean anything is skipped, it is equivalent to leaving third param empty.

Look the next example, still we have

temp = "maple_string"

See how we get every second character from maple_string

Image description

Few more examples where we can get empty strings and full string by writing less

Image description

Some more code you should look at -

Image description

Program to reverse a string

Image description

reversed returns hexadecimal value, so we use join with empty string to make it string again.

More example of using JOIN with STRING

Image description

In the output, its 5 after every character of string

#temp[5] = 'y'
#string does not support updation like this, either convert to list or slice then join
Enter fullscreen mode Exit fullscreen mode

How to update/delete from a string

# Python Program to Update 
# character of a String 

String1 = "Hello, I'm a Geek"
print("Initial String: ") 
print(String1) 

# Updating a character of the String 
## As python strings are immutable, they don't support item updation directly 
### there are following two ways 
#1 
list1 = list(String1) 
list1[2] = 'p'
String2 = ''.join(list1) 
print("\nUpdating character at 2nd Index: ") 
print(String2) 

#2 
String3 = String1[0:2] + 'p' + String1[3:] 
print(String3) 

Enter fullscreen mode Exit fullscreen mode

Some more methods on string

Image description

Update entire string is comparatively easier

# Python Program to Update 
# entire String 

String1 = "Hello, I'm a Geek"
print("Initial String: ") 
print(String1) 

# Updating a String 
String1 = "Welcome to the Geek World"
print("\nUpdated String: ") 
print(String1) 

Enter fullscreen mode Exit fullscreen mode

Deleting a character

# Deleting a character 
# of the String 
String2 = String1[0:2] + String1[3:] 
print("\nDeleting character at 2nd Index: ") 
print(String2) 
Enter fullscreen mode Exit fullscreen mode

Delete entire string, easier

del String1 
Enter fullscreen mode Exit fullscreen mode

String REPLACE

string = "Hello World"
new_string = string.replace("Hello", "Good Bye")

print(new_string)

Enter fullscreen mode Exit fullscreen mode

The output we'll get here is - Good Bye World

It does not change the original string but returns a new one. It is mostly used in string substitution.

# Prints the string by replacing only 3 occurrence of 'ek' by 'a'

print(string.replace("ek", "a", 3))
Enter fullscreen mode Exit fullscreen mode

Output -

geas for geas geas geeks geeks

Image description

END.

Thanks for reading
Will learn more about input and input formatting in upcoming blogs

Top comments (0)