Two variables with strings are our starting point. To extract characters in specific positions we will use brackets [0]
, for example, to extract first character.
In Python, and most other programming languages we count from 0, and not from 1, when we talk about positions/indexes.
a = "Double Quotes"
b = 'Single Quotes'
print("First char from a var: ", a[0])
print("First char from b var: ", b[0])
Result:
First char from a var: D
First char from b var: S
>>>
Following same principle, we can get multiple characters, at different positions:
a = "Double Quotes"
b = 'Single Quotes'
print(a[0], a[1], a[2])
print("")
print(b[0], b[1], b[2])
Result:
D o u
S i n
>>>
We can extract characters in specific range:
print(b[0:7])
Result:
Single
>>>
Last character in string:
print(b[-1])
Result:
s
>>>
To grab everything, use colons:
print(b[:])
Result:
Single Quotes
>>>
How to Remove Spaces in Strings
If we have a "dirty" string with a lot of unwanted spaces, we can use strip()
function:
a = " Double Quotes"
b = 'Single Quotes '
print(a.strip())
print(b.strip())
Result:
Double Quotes
Single Quotes
>>>
After we are done, concatenation is possible. Or, some other operation:
a = " Double Quotes"
b = 'Single Quotes '
print(a.strip() + " " + b.strip())
Result:
Double Quotes Single Quotes
>>>
Ok, in next tutorial we will play with string length, and how to transform characters (lowercase, uppercase).
No comments:
Post a Comment