Academic Resource Center

Strings in Python

Updated on

A “string” is a text that could be just one letter, a group of letters (characters), a phrase, sentence, or a paragraph.

Defining a string

Example code:

Strings in Python.pdf - Google Drive - Google Chrome
1. string1 = 'Welcome!'
2. print(string1)
Click to copy

Output:

Welcome!
Click to copy

Line 1: A string can be defined using a variable. The variable is string1 and the ‘=’ sign means we are assigning it to ‘Welcome’

Note that we use quotation marks around the word or sentence. We can use single or double quotes

Anything that is typed inside the set of quotation marks would be displayed including numerals, spaces and punctuation marks!

Line 2: Would display string1 in the output screen

Example code:

Strings in Python.pdf - Google Drive - Google Chrome

Joining strings: Concatenation

Joining two strings is called concatenation. Strings are joined using the ‘+ ’ sign. Putting the ‘+’ between the strings lets Python know that you are joining them.

Joining two string variables:

Example code:

Document1 - Word

Line 4: aString and bString are joined using the ‘+’ operator and assigned to newString variable.

Line 5: prints newString. Notice that there is no space between the strings. A space can be added inside the quotes if needed.

Strings can also be joined in the print statement using a comma.This adds a space between the variables

Example code:

Strings in Python.pdf - Google Drive - Google Chrome

Joining a string literal to string variables:

Example code:

Strings in Python.pdf - Google Drive - Google Chrome

Joining a string to a number:

A number can be joined to the string using the ‘str()’ function. This converts the number to a string. If this is not done, an error will be thrown, as Python would think you are mathematically adding a text to a number

Example code:

Strings in Python.pdf - Google Drive - Google Chrome

Line 3: Joining without ‘str()’ before aNumber will throw one of the above errors.

Strings in Python.pdf - Google Drive - Google Chrome

Line 3: Joining with str followed by a number in parenthesis removes the error.

Need More Help?

Click here to schedule a 1:1 with a tutor, coach, and or sign up for a workshop. *If this link does not bring you directly to our platform, please use our direct link to "Academic Support" from any Brightspace course at the top of the navigation bar.   

Previous Article Python: Conditionals (with Video)
Next Article Escape Sequences in Python
Have a suggestion or a request? Share it with us!