3.1. Strings Basics#

  • In Python, text is represented as a string, which is a sequence of characters (letters, digits, and symbols).

  • In Python, we indicate that a value is a string by putting either single or double quotes around it.

3.1.1. Operations on Strings#

  • len(string) – to get length of a string

  • + – can add strings, but not str and type float or int

  • * – to repeat a string

  • += – add to another string and save value

  • int("3") – convert str to int

  • float("3.4") – convert str to float

  • str(<input>) – convert the input to a string data type. Useful for converting numbers to strings so you can concatenate strings and numbers.

3.1.2. Single Quotes vs Double Quotes#

'Aristotle'
"Issac Newton"

3.1.3. Triple Quotes for String Literal#

'''Should you want a string
​ 	that crosses multiple lines,
​ 	Use matched triple quotes.'''
"""
This is a string literal. 
        Spaces are printed as is. 
  Hello there!"""

3.1.4. Printing in Python#

print('abbcd', 2, 3)
print('abbcd', 2, 3, sep='\n') # default separator is space

3.1.5. Determining the length of a string#

scientist = 'Issac Newton'
print(len(scientist))

3.1.6. Concatenating Strings#

'Alan Turning' + ' ' + 'Grace Hopper'
'NH' + 3 # This will not work. You cannot add a str and int type. 
'Four score and ' + str(7) + ' years ago'

3.1.7. Converting Strings to Numbers#

int('0')
int('11')
int('-324')
float('-324.40')

3.1.8. Repeating Strings#

'AT' * 5
'-' * 5

3.1.9. Using Special Characters in Strings#

  • How would you put a single quote inside a string that is declared using a single quote?

  • '\\' – how would you print /\/\

  • '\n'

  • '\''

  • '\"'

  • '\t' – useful for parsing TSV files

3.1.10. Getting information from the Keyboard#

number = input('Please enter a number: ')
  • Input returns a str data type.

Warning

Input arguments to a function are not the same as the input function!

3.1.11. Converting Numeric Values#

number = int(input('Please enter a number: '))
def convert_celsius(fahrenheit):
    return (fahrenheit - 32.0) * 5.0 / 9.0    
def convert_celsius():
    fahrenheit = float(input('Please enter temperature in Fahrenheit: '))
    celsius =  (fahrenheit - 32.0) * 5.0 / 9.0  
    print('The temperature in celsius is: ', celsius)