Mastery 26. Creation and use of strings

Strings are bits of text, and the syntax for them is anything written between quotes, as the following example:

>> string1=”Hello World”

In this example we are assigning the string to a variable called string1 which we can print, as we have learned in later posts, but printing it is not the only action we can do with strings, there are many more operations we can perform with strings and I will show you some of them in this post.

One operation that we can do is getting to know the lenght of our string by the len() statement. Example:

>>print len(string1)

This will print 11 because the string is 11 characters long, including spaces.

 

Another operation with strings is performed by the index staement, this will tell us the position of a given letter. Example:

>> print string1.index(“W”)

For this example, it will get printed 6, because W is in the 6th position, if we start counting from 0.

 

Also, a cool operation that we can do with strings is printing just a part of the whole string, for example:

>>print string1[4:8]

This will print “o Wo” because is the part of the string that goes from the 4th letter (starting from 0) to the 7th letter ( the end boundary it is not taken into account)

 

Another interesting functions are the following:

>>print string1.upper()
>>print string1.lower()

Which will print a new string with all letters converted to uppercase and lowercase respectively.

 

There are so many other operations that we can do with strings, such as concatenation, multiplication, etcetera.

If you are interested in learning more about strings, you can check this link: https://docs.python.org/2/library/string.html

 

 

CC BY 4.0 Mastery 26. Creation and use of strings by Manuel Madrigal is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.