Python Tutorial-Strings

A String is a sequence of characters. As with most programming languages Strings are one of the most important parts of designing a program. Strings can contain almost any character. Let’s take a look at a simple example of a string.

That will print out This is my string when you run it. Simple enough, right? What if I wanted to know what type of variable I have? I can do that by adding a type in front of the variable, like this.

This outputs class str. This can be very useful when debugging your code. Let’s try a different one.

This outputs class int because your variable is an integer.

Strings are very powerful and very easy to declare. Let’s take a look at some of the other methods that can be used for strings:

stringVar.count(‘x’) – counts the number of occurrences of ‘x’ in stringVar
stringVar.find(‘x’) – returns the position of character ‘x’
stringVar.lower() – returns the stringVar in lowercase (this is temporary)
stringVar.upper() – returns the stringVar in uppercase (this is temporary)
stringVar.replace(‘a’, ‘b’) – replaces all occurrences of a with b in the string
stringVar.strip() – removes leading/trailing white space from string

Another cool feature in regards to Strings in Python is the ability to break it down by index. What I mean by that is you can have Python output parts of your string by calling it’s index number. Let’s take a look.

[datacamp_exercise lang="python" height="450"]
[datacamp_pre_exercise_code]
myString = "My String"
print (myString[3:9])
print (myString[:5])
[/datacamp_pre_exercise_code]
[datacamp_sample_code]
myString = "My String"
print (myString[3:9])
print (myString[:5])
[/datacamp_sample_code]
[datacamp_solution]
myString = "My String"
print (myString[3:9])
print (myString[:5])
[/datacamp_solution]
[datacamp_sct]
myString = "My String"
print (myString[3:9])
print (myString[:5])
[/datacamp_sct]
[datacamp_hint]
myString = "My String"
print (myString[3:9])
print (myString[:5])
[/datacamp_hint]
[/datacamp_exercise]
Your output should be String and My St. For the first print statement you want to know how we started with S and ended with g, right? Well remember Python starts indexing with a 0. That means M equals index 0, y=1 the space is 2 and S=3. Then the reason we end with the 8th character is because Python stops before the last index..think of it like a For Loop…we wanted all the characters up to 9.

For the second print statement you might be wondering how did you get that result. By leaving the first index number blank Python assumes it’s a 0 and starts counting from the first character. Remember Python always starts with 0.

That’s it for now..go take a nap.