String Operations in Python
First string operation to discuss is concatenation
. This operation allows us to combine multiple strings together.
1var book = "The Great Gatsby";
2var author = "F. Scott Fitzgerald";
3
4var sentence = book + "was written by " + author;
5
6console.log(sentence); //prints "The Great Gatsby was written by F. Scott Fitzgerald"
Multiplication operator *
, allows to create a string which repeats itself multiple times. For example,
PYTHON
1name = "Chris"
2
3print(name*3) #prints "ChrisChrisChris"
Other string operations in Python are all implemented through string methods. Let's see some of the examples below.
len()
method tells us the length of string.count()
method tells about the number of times a specified value occurs in string.upper()
method converts all the characters in the string to uppercase.
Example usage of these operations can be found in the code block below.
1var book = "The Great Gatsby";
2var author = "F. Scott Fitzgerald";
3
4console.log(book.length); // prints 16
5console.log(author.indexOf("z")); // prints 12
6console.log(author.indexOf("Scott")); // prints 3
7console.log(author.toLowerCase()); // prints "f. scott fitzgerald"
A comprehensive list of string methods is provided here.