Image

Anyone Can Code.





Image

String Operations

Sammarth Kumar




Index

  1. Concatenation
  2. Repetition
  3. Membership
  4. Slicing

Concatenation

Concatenation simply means to join. Python supports joining strings together with the addition operator + (pretty cool right?).

1
2
3
4
str1 = "Q-"
str2 = "Programming"
concatenated = str1+str2
print(concatenated)

Output

Q-Programming

Keep in mind that since whitespace is counted as a character, concatenation will not result in the creation of whitespaces between words, unless specified beforehand.

Let's look at the next two code blocks to see how.

1
2
3
word1 = "Hello"
word2 = "World"
print(word1 + word2)

Output

HelloWorld

1
2
3
word1 = "Hello "
word2 = "World"
print(word1 + word2)

Output

Hello World

As you can see in the second block, we left a space after "Hello". This space is counted as a character and hence we get the output "Hello World"

Repetition

Python allows users to repeat srings using the * operator. They must always be multiplied by a positive integer.

1
2
word = "QP"
print(word * 5)

Output

QPQPQPQPQP

Membership

Python has two membership operators in and not in. As the names suggest, these are used to check whether a character or set of characters is in a particular string or not. The final result will be a Boolean - either True or False.

Example of in:

1
"H" in "Hello"

Output

True

Example of not in:

1
"H" not in "Hello"

Output

False

Slicing

Slicing is used to extract certain sections of a string, through specifying an index range and step value.

You know what indices are, but what is a step value? Simply put, a step value is the difference between the integer values of indices. For example, if the index range is 0:8 and the step value is 2, the program will access every second character of the string i.e. 0,2,4,6

Note how we didn't include 8. This is because the upper limit is not counted, only the indices from the lower limit to the index preceding the upper limit.

1
2
3
4
string = "Q-Programming"
print(string[2:10])
print(string[2:10:3])
print(string[-2:-10:-2])

Output

Programm
Pgm
nmag

That's it for this tutorial! Scroll up and click on Next for the next tutorial!

For information on how you can use this information, please refer to our Terms of Use


Copyright © 2020, Q-Programming | Created by Arjun Sodhi, Balpreet Juneja and Sammarth Kumar | Developed and Designed by Sammarth Kumar