Example 1 - String Assignment
name = input('What is your name? ')
print(name)
Example 2 - String concatenation
subject = 'Mrs Smith'
verb = 'runs'
object = 'home'
sentence = subject + verb + object
print(sentence)
sentenceWithSpaces = subject + ' ' + verb + ' ' + object
print(sentenceWhithSpaces)
Example 3 - Length of a string
lengthOfSentence = len('This is a sentence')
print(lengthOfSentence)
Example 4 - Output strings and numbers
age = 15
name = 'Amy'
height = 159.3
print('Hi ' + name + ', your are age ' + str(age) + ' and ' + str(height) + ' cm tall.')
Example 5 - Get the character in the nth position in the string
sentence = 'My Python program'
a = sentence[0]
b = sentence[5]
print(a)
print(b)
Note |
The characters in a string are numbered starting at 0 (zero). |
Example 6 - Looping through a string (method 1)
name = 'hello'
for letter in name:
print(letter)
Example 7 - Looping through a string (method 2)
name = 'hello'
for i in range(len(name)):
print('Character number ' + str(i) + ' is: ' + name[i])
Example 8 - Strip (remove whitespace characters)
sentence = ' this is some text. '
sentenceStripped = sentence.strip()
print(sentence)
print(sentenceStripped)
Example 9 -Split (split a string into smaller strings)
gameDetails = 'pacman,1980,Japan,Namco'
listOfDetails = gameDetails.split(',')
gameName = listOfDetails[0]
year = listOfDetails[1]
country = listOfDetails[2]
company = listOfDetails[3]
print(listOfDetails)
print(gameName + ' was created in ' + year + ' and made in ' + country + ' by ' + company)
Example 10 - Lower (to convert characters to lowercase)
name = 'Jacob SMITH'
nameInLowercase = name.lower()
print(nameInLowercase)
Example 11 - Upper (testing an input)
name = 'sMith'
if name.upper() == 'SMITH':
print('Your name is SMITH')
Example 12 - Isnumeric (find if a string contains digits only)
a = 'hello456'
b = '456'
c = '456.23
d = '-23'
print(a.isdigit())
print(b.isdigit())
print(c.isdigit())
print(d.isdigit())
Example 13 - Find left character of a string (slice)
phrase = 'hello everyone'
print(phrase[:7]) #Find first seven characters
Example 14 - Find right character of a string (slice)
phrase = 'hello everyone'
print(phrase[7:]) #Find last seven characters
Example 15 - Find substring between twoo points (slice)
phrase = 'hello everyone'
print(phrase[2:8])