In this tutorial, you will learn about strings in python. You will learn what is string and how to access, concatenate strings in python.
What are the strings in python?
String is a sequence of characters. You can create a string in python by enclosing strings in either single, double, or triple quotes.
Example:
print('Hello World')
Output:
Hello World
Multiple line strings:
You have to use triple consecutive single or double quotes if you want to use multiple lines of string. By using multiline strings you can create strings to span multiple lines, include NEWLINE, TAB, and other special characters
Example of multiline string using triple consecutive single quotes:
print('''Welcome to python tutorial.
It is easy to learn.''')
Output:
Welcome to python tutorial.
It is easy to learn.
Example of multiline string using triple consecutive double quotes:
print("""Welcome to python tutorial.
It is easy to learn.""")
Output:
Welcome to python tutorial.
It is easy to learn.
Concatenation of strings:
You can join multiple strings using concatenation.
Example:
str1 = "Hello"
str2 = "World"
print("Concatenated string is: ", str1 + str2)
Output:
Concatenated string is: HelloWorld
Accessing characters from strings:
To get the character from a specific index, you have to put the index of character into []. Index of string starts with 0.
Example:
message = 'Welcome to python tutorial'
print(message[0])
Output:
W
By passing negative index, string character result displayed in a reverse manner.
Example:
message = 'Welcome to python tutorial'
print(message[-1])
Output:
l
If you want to get a specific part of the string, can get it by putting indexes from start to end between : character.
Example:
message = 'Welcome to python tutorial'
print(message[0:7])
Output:
Welcome
**Note: Last index character does not get returned.
If you want to get the rest of the full string from a specific character, you can get it like following:
Example:
message = 'Welcome to python tutorial'
print(message[11:])
Output:
python tutorial
If you want to get a specific string from starting to a specific character you can get it like following:
Example:
message = 'Welcome to python tutorial'
print(message[:7])
Output:
Welcome
If you don’t mention indexes between : then the whole string gets returned.
Example:
message = 'Welcome to python tutorial'
print(message[:])
Output:
Welcome to python tutorial
Conclusion:
In this tutorial, you learned about strings in python. You also learned how to access, concatenate strings in python. If you have problems while implementing code, you can ask me through the comment section.