How to access and use string values in Python
Concatenating Strings
We can use + operator to append two strings together.
print "Hello, " + "world!"
x = "Hello, "
y = "world!"
print x + y
The code above generates the following result.
String repitition
Multiplying a string by a number x creates a new string where the original string is repeated x times.
The following code prints out dashes in an easy way.
print '-'*80 # 80 dashes, the easy way
print "Pie" * 10
Useful Values from the string Module
Constant | Description |
---|---|
string.digits | A string containing the digits 0?9 |
string.letters | A string containing all letters (upper- and lowercase) |
string.lowercase | A string containing all lowercase letters |
string.printable | A string containing all printable characters |
string.punctuation | A string containing all punctuation characters |
string.uppercase | A string containing all uppercase letters |
The following code checks the string value.
import string# w ww. jav a2s . c o m
alphas = string.letters + '_'
nums = string.digits
myInput = "input"
if myInput[0] not in alphas:
print '''invalid: first symbol must be alphabetic'''
else:
for otherChar in myInput[1:]:
if otherChar not in alphas + nums:
print '''invalid: remaining symbols must be alphanumeric'''
break
else:
print "okay as an identifier"
The code above generates the following result.