首页>itarticle>python course 2 week 1 Index of Strings Get the Length of a String Looping through Strings Slicing Strings String Concatenation Check if one string ‘is’ in another string Searching a String Make Uppercase Search and Replace Stripping Whitespace Prefixes
python course 2 week 1 Index of Strings Get the Length of a String Looping through Strings Slicing Strings String Concatenation Check if one string ‘is’ in another string Searching a String Make Uppercase Search and Replace Stripping Whitespace Prefixes
admin11月 13, 20200
String manipulation in Python 3.
Use input() function The input data is string, needed to be converted to other data types if necessary, for example, num = int(str)
1 2 3 4
name = input('Enter a name: ') print(name)
# Tracy
Index of Strings
1 2 3 4 5
fruit = 'banana' print(fruit[0]) # output: b. Pronouncation: fruit sub 0 x = 3 w = fruit[x - 1] print(w) # output: n
Get the Length of a String
len() function
1
print(len(fruit)) # output: 6
Looping through Strings
1 2 3 4 5 6 7 8 9 10 11
# while loop index = 0 while index < len(fruit): letter = fruit[index] print(index, letter) index += 1 print('Done') # for loop for letter in fruit: print(letter) print('Done')
Slicing Strings
Use the colon operator, ‘start’:’end’
The first number is including, the second number is excluding.
If the second number is beyond the end of this string, it gets the rest of the string.
1 2 3
s = 'Tracy Yang' print(s[0:4]) # output: Trac print(s[4:20]) # output: y Yang
No first number: get the substring from 0 (including) to the second number (excluding)
No second number: get the substring from the first number (including) to the end
Just colon operator: get the whole string
1 2 3
print(s[:2]) #Tr print(s[8:]) #ng print(s[:]) #Tracy Yang
String Concatenation
1 2 3 4 5
a = 'Hello' b = a + 'There' print(b) # output: HelloThere c = a + ' ' + 'There' print(c) # output: Hello There
近期评论