Python String Basics

Introduction

Strings are called what they are because they are strings of characters. It doesn’t matter if those characters are letters, numbers, symbols or spaces. They are all taken literally and not processed within a string. That’s why strings are sometimes referred to as string literals.

String Basics

If you’ve been following along with the previous guides, you’ve already experimented with some strings. You’ve typed in some, and you’ve printed them back out. What about getting user input when the Python script runs? Python has built in functionality to take in user input and assign it to a variable. Try it out.

user_input = input("Please enter some text: ")
print(user_input)

The script will begin by asking, “Please enter some text: ” and waiting for the user to do so. It will then print out whatever the user
entered. This method doesn’t just work with strings. You can get numbers or other variables from it too, but you have to tell it what type you’re working with.

Adding Strings Together

That’s a nice trick, but you’ve got to be bored with just entering strings, either way. What about actually doing something with them? Well, you can do a lot with strings. The easiest thing that you can do is something that you already tried earlier on, combining strings. Try making your script ask a user for their name, and say “Hello” to them.

name = input("What's your name? ")
print("Hello " + name + "!")

Not bad, right? You don’t have to just print out that new user input variable either. You can add strings together before you print them out.

name = input("What's your name? ")
message_greeting = "Hello " + name + "!"
message_compliment = name + " is a nice name."
message = message_greeting + message_compliment
print(message)

Notice something? Python just smashed the message parts together again. There’s a way around that, but it sort of breaks that idea of strings being completely literal.

name = input("What's your name? ")
message_greeting = "Hello " + name + "!"
message_compliment = name + " is a nice name."
message = message_greeting + "\n " +  message_compliment
print(message)

Python didn’t smash them together again, but you’re probably wondering what the deal is with that weird \n. Occasionally, there will be instances where you can’t express what you need to exactly in a literal string. What would happen if you had to output text with quotes in it, for example? That’s why there are special characters called escape sequences. Escape sequences allow you to insert problematic characters into strings, and they are always preceded by a \. So, if you wanted to include quotes, you would just escape the quotation marks like this, \"This is a quote\". That character that you saw in the last example was the newline character. It tells Python that it should break the text up onto the next line. Since you can’t just hit “Enter” in the middle of a string, you include "\n".

Combining Strings and Numbers

So, what if you wanted to add a number to a string? Try this out.

print("The answer is " + 42)

That didn’t go well, did it?

>>> print("The answer is " + 42)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: Can't convert 'int' object to str implicitly

You can’t just add numbers and strings together, but there are some ways to tell Python that you want it to treat the number like a string. The first way is to convert the number to a string.

print("The answer is " + str(42))

Using str() temporarily converts the number in the parenthesis to a string. It doesn’t save those changes to a variable if you’re using it on one. You can use it to save changes to a variable, though.

answer = 42
# The variable "answer" is now an integer
answer = str(answer)
# Now it's a string

Using str() can be sort of cumbersome when you just want to print out a line of information, plus it requires more code to run. It also can get confusing if you have multiple numbers in one string of text. There’s another way to put placeholders into a string and specify what variables they correspond to. This is a much cleaner and more dynamic way of handling numbers in strings.

answer = 42
print("The answer is %d" % answer)

In the above example, %d is a placeholder for an integer. There are other placeholders too. %f is a placeholder for floats, and %s is a placeholder for strings. The % separates that string from the variable(s) that will be substituted in.

You can use multiple placeholders and multiple variables in the same string. All that you have to do is specify them in a set of parenthesis after the % character. Be sure that they are in order and the types match their placeholders.

first_number = 10
second_number = 12.5
sum = first_number + second_number
print("The sum of %d and %f is %f" % (first_number, second_number, sum))

The floats are a bit long, but you can see that it works. If you want shorter floats in your string, you can specify the decimal place like this, %.2f. That limits the float to the second decimal place.

Conclusion

This first part of the guide focused on some of the most basic things that you can use strings for in Python. It covered combining strings and incorporating other variable types into strings. Practice the different ways of combining strings, especially using the %. The next guide is going to go much deeper into strings and will begin pulling them apart… quite literally.

Table of Contents

  1. Python Introduction and Installation Guide
  2. Python Files and the Interpreter
  3. Experimenting With Numbers and Text In Python
  4. Python Variables
  5. Working With Number Variables In Python
  6. Python String Basics
  7. Advanced Python Strings
  8. Python Comments
  9. Python Lists
  10. Python List Methods
  11. Python Multidimensional Lists
  12. Python Tuples
  13. Python Boolean Operators
  14. Python If Statements
  15. Python While Loops
  16. Python For Loops
  17. Python Dictionaries
  18. Python Advanced Dictionaries
  19. Python Functions


Comments and Discussions
Linux Forum