As string is an datatype .Here you come to know about how to create a string and different operation on String.
How to Create a String in Python
You can create a string in three ways using single, double or triple quotes. Here’s an example of every option:
Basic Python String
my_string = “Let’s Learn Python!” another_string = ‘It may seem difficult first, but you can do it!’ a_long_string = ‘’’Yes, you can even master multi-line strings that cover more than one line with some practice’’’
IMP! Whichever option you choose, you should stick to it and use it consistently within your program.
As the next step, you can use the print() function to output your string in the console window.
This lets you review your code and ensure that all functions well. Here’s a snippet for that:
print(“Let’s print out a string!”)
Concatenation — a way to add two strings together using the “+” operator. Here’s how it’s done:
string_one = “I’m reading “ string_two = “a new great book!” string_three = string_one + string_two
Note: You can’t apply + operator to two different data types e.g. string + integer. If you try to do that, you’ll get the following Python error:
TypeError: Can’t convert ‘int’ object to str implicitly
As the name implies, this command lets you repeat the same string several times. This is done using * operator. Mind that this operator acts as a replicator only with string data types. When applied to numbers, it acts as a multiplier.
String replication example:
‘Alice’ * 5 ‘AliceAliceAliceAliceAlice’
And with print ()
And your output will be Alice written five times in a row.
For reference, here’s a list of other math operations you can apply towards numbers:
How to Store Strings in Variables
Variables in Python 3 are special symbols that assign a specific storage location to a value that’s tied to it. In essence, variables are like special labels that you place on some value to know where it’s stored.
Strings incorporate data.
So you can “pack” them inside a variable. Doing so makes it easier to work with complex Python programs.
Here’s how you can store a string inside a variable
my_str = “Hello World”
Let’s break it down a bit further:
- my_str is the variable name.
- = is the assignment operator.
- “Just a random string” is a value you tie to the variable name.
Now when you print this out, you receive the string output.
= Hello World
See? By using variables, you save yourself heaps of effort as you don’t need to retype the complete string every time you want to use it.