String字符串问题

  1. str and Unicode

str(byte flow)

Unicode(string flow)

 

  1. ASCII(1 byte(7bits+1bit sign) represents 1char, most 127 chars)
    1. à ISO-8859-1(8bits,most 256 chars) à
    2. (GB: Chinese) GB2312 àGBK à GB18030
  2. Unicode(ucs-2, ucs-4) (cost space + time)
  3. UTF-8(efficiency) à UTF-32

Process Chinese string: GBK->Unicode->UTF-8

Decode: GBKàUnicode

Encode: UnicodeàGBK

###################################################################

*****************************************************************

#example 1 & example 2

import sys
print(sys.stdin.encoding) #Current: utf-8
print(sys.stdout.encoding) #Current: utf-8

x = input(u"请输入名字: ".encode(sys.stdout.encoding).decode(sys.stdout.encoding))# encodeError solution: ".encode('gbk') "
f = open('1.txt', 'w')
                                         
#Current
f.write(x.encode(sys.stdin.encoding).decode(sys.stdin.encoding))
f.close()

String字符串问题

String字符串问题

*****************************************************************

#example 1

import sys
print(sys.stdin.encoding) #Current: GBK    # input to txt

print(sys.stdout.encoding) #Current: GBK   # output to screen
                          #
你的系统已经是GBK编码了,其实你不需要编码再解码,多余
x = input(u"请输入名字: ".encode(sys.stdout.encoding).decode('GBK'))


f = open('1.txt', 'w')
       
#Current text format:GBK,因此以下也是多余
f.write(x.encode(sys.stdin.encoding).decode('GBK'))
f.close()

String字符串问题*****************************************************************

#example 2
import sys

print(sys.stdin.encoding) #Current: utf-8   # input to cpu

print(sys.stdout.encoding) #Current: utf-8  # output to screen



x = input(u"请输入名字: ".encode(sys.stdout.encoding).decode('utf-8'))# encodeError solution: ".encode('gbk') "

f = open('1.txt', 'w')

                                          #Current

f.write(x.encode(sys.stdin.encoding).decode('utf-8'))

f.close()

String字符串问题

*****************************************************************

###################################################################

将字符串中的字符的每一个字母转换成大写,这种题目是一个大坑!

譬如下列题目:

 

You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.

这个时候大多数人会这样写

def solve(s):

    strList = s.split()

    newStr=""

    for i in range(len(strList)):

        if strList[i][0].isalpha():

            newStr+=strList[i][0].upper()+strList[i][1:]

        else:

            newStr+=strList[i]

        newStr+=' '

       

return newStr.strip()

但是程序运行的结果: 有些测试是对的 有些测试是错的;换句话说就是通不过

原因是 题目没有告诉你:

这个字符串到底有多少个空字符分隔每个字符

所以建议的方法是使用原位替换str.replace(elem, elem.capitalize())

String字符串问题

def solve(s):

    for strElem in s.split():

        #replace is replace an-element with an-new-element in-place

        s=s.replace(strElem, strElem.capitalize())

       

    return s

 

print(solve(“hello world       lol”))
the correct output:Hello World       Lol
 
not the wrong output: Hello World Lol
#################################################################
又一个统计学大坑
涉及统计学的概念:
将n个数字进行排序 得到多少种不同的 结果:n+n-1+n-2+…+1

String字符串问题String字符串问题String字符串问题

def minion_game(string):

    # your code goes here

    #BANANA: length=6: total probabilities: 6+5+4+3+2+1=21

    #BAANANAS: length=8: total probabilities: 8+7+6+5+4+3+2+1=36

    #Then separate these probabilities to two people or divide it by two

   

    kScore = 0

    sScore = 0

    for i in range(len(string)):

        if string[i] in 'AEIOU':

            kScore += (len(string)-i)

        else:

            sScore += (len(string)-i)

 

    if sScore>kScore:

        print("Stuart",sScore)

    elif sScore<kScore:

        print("Kevin",kScore)

    else:

        print("Draw")


************************************************************

String字符串问题

def swap_case(s):

    return ''.join([c.lower() if c.isupper() else c.upper() for c in s])

 

def print_full_name(a, b):

    print("Hello %s %s! You just delved into python." % (a,b))

Hello Ross Taylor! You just delved into python.

*******************************************************************************

print( str(any(c.isalnum()  for c in s))+'\n'+

    str(any(c.isalpha()  for c in s))+'\n'+

    str(any(c.isdigit()  for c in s))+'\n'+

    str(any(c.islower()  for c in s))+'\n'+

    str(any(c.isupper()  for c in s))

)

 

r_list=list([False,False,False,False,False])

 

for c in s:

    r_list[0] |= c.isalnum()

    r_list[1] |= c.isalpha()

    r_list[2] |= c.isdigit()

    r_list[3] |= c.islower()

    r_list[4] |= c.isupper()

 

for i in r_list:

print(i)

*******************************************************************************

 

def print_rangoli(size):

    # your code goes here

    import string

    alpha = string.ascii_lowercase

    aList=[]

    for i in range(n):

        s="-".join(alpha[i:n]) #if i=0: a-b-c-d-e...

        aList.append( (s[::-1]+s[1:]).center(4*size-3, '-') )

    print("\n".join(aList[::-1]+aList[1:]) )

 

String字符串问题

String字符串问题