Strings

  • String basics
  • String formatting

string is a sequence of characters

Example: abrakadabra, 

We can store it and associate a name/variable with it.

To strings like "hi" or 'broom', we refer to as a string literal in a Python program.



What can I do with strings in Python?

>>> firstPart = "abra"
>>> secondPart = "kadabra"

>>> firstPart[2]
'r'
>>> secondPart[0]
'k'
>>> secondPart[2:]
'dabra'
>>> secondPart[1:4] 
'ada'
>>> firstPart + secondPart 
'abrakadabra'
>>> len(firstPart) 
4
>>> firstPart+"cloud"
'abracloud'
>>> firstPart+'/'+secondPart
'abra/kadabra'
>>> firstPart*3
'abraabraabra'
>>> firstPart
'abra'

 

String formatting

Program output commonly includes the value of variables as a part of the text. 

Example: for the following code:

num = 18
tum = 9.8
print("I have a number",num,"and a number",tum)

will produce:

I have a number 18 and a number 9.8

Note that we have to keep track of those double quotes (") and commas in the print statement.

 

Compare the following two print statements:

num = 18,tum = 9.8
print("I have a number",num,"and a number",tum)
print("I have a number %d and a number %f" % (num,tum))

The first one produced:

I have a number 18 and a number 9.8

The second one produced:

I have a number 18 and a number 9.800000

 

A string formatting expression allows a programmer to create a string with placeholders that are replaced by the value of variables.

Such a placeholder is called a conversion specifier. Different conversion specifiers are used to perform a conversion of the given variable value to a different type when creating the string. 

Example:

num = 5.5
print("The integer part is %d" % num)

will yield:

The integer part is 5

 

Example: Consider the following code fragment

price = 119 # in dollars
discount = 30 # in percent %
print("A $%d jacket at %d%% discount is now priced at %f" % (price,discount,price*0.7))

Produces the output:

A $119 jacket at 30% discount is now priced at 83.300000

 

Example: Consider the following code fragment:

name1 = "Chris"
name2 = "John"
print("%s and %s are heading to the movies tonight" % (name1,name2))

Produces the output:

Chris and John are heading to the movies tonight

 


Source: City University of New York, https://academicworks.cuny.edu/bx_oers/29/
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 License.

Last modified: Tuesday, 16 February 2021, 12:38 PM