Strings and Variables in Python

Strings

A string is simply a series of characters. Anything inside quotes is considered a string in Python,and you can use single or double quotes around your strings like this:

This is a string."
'This is also a string.'

Changing Case in a String with Methods

One of the simplest tasks you can do with strings is change the case of the words in a string.Look at the following code, and try to determine what’s happening:

name = "string python"
print(name.title())

Save this file as name.py, and then run it. You should see this output:

String Python

In this example, the lowercase string “string python” is stored in the variable name. The method title() appears after the variable in the print() statement. A method is an action that Python can perform on a piece of data. The dot (.) after name in name.title() tells Python to make the title() method act on the variable name. Every method is followed by a set of parentheses, because methods often need additional information to do their work. That information is provided inside the parentheses. The title() function doesn’t need any additional information, so its parentheses are empty. Title() displays each word in titlecase, where each word begins with a capital letter.

This is useful because you’ll often want to think of a name as a piece of information. For example, you might want your program to recognize the input values String, STRING, and string as the same name, and display all of them as String. Several other useful methods are available for dealing with case as well. For example, you can change a string to all uppercase or all lowercase letters like this:

Example#01:

The method upper() returns a copy of the string in which all case-based characters have been uppercased. The method lower() returns a copy of the string in which all case-based characters have been lowercased.

The lower() method is particularly useful for storing data. Many times you won’t want to trust the capitalization that your users provide, so you’ll convert strings to lowercase before storing them. Then when you want to display the information, you’ll use the case that makes the most sense for each string.

Combining or Concatenating Strings

When applied to strings, the + operation is called concatenation. It produces a new string that is a copy of the two original strings pasted together end-to-end. Notice that concatenation doesn’t do anything clever like insert a space between the words. The Python interpreter has no way of knowing that you want a space; it does exactly what it is told.

Strings can be concatenated with the ‘+’ operator and repeated with ‘*’

Example#02:

Indexing of string

Like the list data type that has items that correspond to an index number, each of a string’s characters also correspond to an index number, starting with the index number 0.

For the string Sammy Shark! the index breakdown looks like this:

As you can see, the first S starts at index 0, and the string ends at index 11 with the ! symbol.

We also notice that the whitespace character between Sammy and Shark also corresponds with its own index number. In this case, the index number associated with the whitespace is 5.The exclamation point (!) also has an index number associated with it. Any other symbol or punctuation mark, such as *#$&.;?, is also a character and would be associated with its own index number.

Accessing Characters by Negative Index Number:

If we have a long string and we want to pinpoint an item towards the end, we can also count backwards from the end of the string, starting at the index number -1. For the same string Sammy Shark! the negative index breakdown looks like this:

By using negative index numbers, we can print out the character r, by referring to its position at the -3 index, like so:

Example#03:

print(ss[-3])

Output:

r

Using negative index numbers can be advantageous for isolating a single character towards the end of a long string.

Slicing Strings:

We can also call out a range of characters from the string. Say we would like to just print the word Shark. We can do so by creating a slice, which is a sequence of characters within an original string. With slices, we can call multiple character values by creating a range of index numbers separated by a colon [x:y]:

Example#04:

print(ss[6:11])

Output:

Shark

When constructing a slice, as in [6:11], the first index number is where the slice starts (inclusive), and the second index number is where the slice ends (exclusive), which is why in our example above the range has to be the index number that would occur just after the string ends.

If we want to include either end of a string, we can omit one of the numbers in the string[n:n] syntax. For example, if we want to print the first word of string ss — “Sammy” —we can do so by typing:

Example#05:

print(ss[:5])

Output:

Sammy

Counting Methods

While we are thinking about the relevant index numbers that correspond to characters within strings, it is worth going through some of the methods that count strings or return index numbers.

This can be useful for limiting the number of characters we would like to accept within a userinput form, or comparing strings. Like other sequential data types, strings can be counted through several methods.

We’ll first look at the len() method which can get the length of any data type that is a sequence,whether ordered or unordered, including strings, lists, tuples, and dictionaries.The len() method counts the total number of characters within a string.

Example#06:

print(len("Let's print the length of this string."))

Output:

38
  • If we want to count the number of times either one particular character or a sequence of characters shows up in a string, we can do so with the count().
  • We can also find at what position a character or character sequence occurs in a string. We can do this with the find() method, and it will return the position of the character based on index number.

Variables

  • Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.
  • Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.
  • Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign(=) is used to assign values to variables.
  • Variable names can contain only letters, numbers, and underscores. They can start with a letter or an underscore, but not with a number. Spaces are not allowed in variable names, but underscores can be used to separate words in variable names.

Example#07

message = "Hello Python world!"
print(message)

Output:

Hello Python world!

We’ve added a variable named message. Every variable holds a value, which is the information associated with that variable. In this case the value is the text “Hello Python world!”

Related Post