Python3 与 C# 基础语法对比(String专栏)

Python3 与 C# 基础语法对比:https://www.cnblogs.com/dotnetcrazy/p/9102030.html

事先声明一下,避免让新手进入误区:不是说Python比NetCore要好,而Python设计的目的就是==》让程序员解放出来,不要过于关注代码本身,那么性能、规范等等各方面隐患就存在了,后面编写一个稍微大点的项目就看出来了。而且不要太受语言约束,之前我也说过,用各自语言的优势来为项目服务~ 这才是开发王道。比如Python用来数据分析,Go用来并发处理等等,不多说了,记住一句话即可:“Net是性价比最高的”

步入正题:欢迎提出更简单或者效率更高的方法

基础系列:(这边重点说说Python,上次讲过的东西我就一笔带过了)

1.输出+类型转换
Python写法:

NetCore:

2.字符串拼接+拼接输出方式

python:

NetCore

3.字符串遍历、下标、切片

重点说下python的下标,有点意思,最后一个元素,我们一般都是len(str)-1,他可以直接用-1,倒2自然就是-2

#最后一个元素:user_str[-1]
user_str[-1]
user_str[len(user_str)-1] #其他编程语言写法
#倒数第二个元素:user_str[-2]

这次为了更加形象对比,一句一句翻译成NetCore(有没有发现规律,user_str[user_str.Length-1]==》-1是最后一个,user_str[user_str.Length-2]==》-2是最后一个。python在这方面简化了

3.2 python切片语法[start_index:end_index:step] (end_index取不到)

# 切片:[start_index:end_index:step] (end_index取不到)
# eg:str[1:4] 取str[1]、str[2]、str[3]
# eg:str[2:] 取下标为2开始到最后的元素
# eg:str[2:-1] 取下标为2~到倒数第二个元素(end_index取不到)
# eg:str[1:6:2] 隔着取~str[1]、str[3]、str[5](案例会详细说)
# eg:str[::-1] 逆向输出(案例会详细说,)

来个案例:我注释部分说的很详细了,附录会贴democode的

NetCore,其实你用Python跟其他语言对比反差更大,net真的很强大了。补充(对比看就清楚Python的step为什么是2了,i+=2==》2)

 

方法系列:

# 查找:find,rfind,index,rindex
Python查找推荐你用 find和rfind
netcore: index0f就相当于python里面的 find

# 计数:count
python: str.count()
netcore:这个真用基础来解决的话,只能自己变形一下: (原字符串长度 - 替换后的长度) / 字符串长度
 
Python补充说明:像这些方法练习用 ipython3就好了( sudo apt-get install ipython3),code的话需要一个个的print,比较麻烦(我这边因为需要写文章,所以只能一个个code)
index查找不到会有异常

# 替换:replace
Python: xxx.replace(str1, str2, 替换次数)
replace可以指定替换几次

NetCore:替换指定次数的功能有点业余,就不说了,你可以自行思考哦~


#连接:join:eg:print("-".join(test_list))

 netcore:string.Join(分隔符,数组)

 

#分割:split(按指定字符分割),splitlines(按行分割),partition(以str分割成三部分,str前,str和str后),rpartition

说下split的切片用法 :print(test_input.split(" ",3)) #在第三个空格处切片,后面的不切了

继续说说 splitlines(按行分割),和split("\n")的区别我图中给了案例
扩展: split(),默认按空字符切割(空格、\t、\n等等,不用担心返回'')
最后说一下 partition r partition 返回是元祖类型(后面会说的),方式和find一样,找到第一个匹配的就罢工了【注意一下没找到的情况】
 
netcore:  split里面很多重载方法,可以自己去查看下,eg:Split("\n",StringSplitOptions.RemoveEmptyEntries)
再说一下这个: test_str.Split('a');//返回数组如果要和Python一样返回列表==》test_str.Split('a').ToList(); 【需要引用linq的命名空间哦】

# 头尾判断:startswith(以。。。开头),endswith(以。。。结尾)

netcore:


# 大小写系:lower(字符串转换为小写),upper(字符串转换为大写),title(单词首字母大写),capitalize(第一个字符大写,其他变小写)

netcore:


# 格式系列:lstrip(去除左边空格),rstrip(去除右边空格),strip(去除两边空格)美化输出系列:ljust,rjust,center
 
 
netcore: Tirm很强大,除了去空格还可以去除你想去除的任意字符
ljust,rjust,center这些就不说了,python经常在linux终端中输出,所以这几个用的比较多。net里面 string.Format各种格式化输出,可以参考
 

# 验证系列:isalpha(是否是纯字母),isalnum(是否是数字|字母),isdigit(是否是纯数字),isspace(是否是纯空格)
一张图搞定,其他的自己去试一试吧,注意哦~  test_str5=" \t \n " #isspace() ==>true
 
netcore: string.IsNullOrEmpty 和 string.IsNullOrWhiteSpace 是系统自带的,其他的你需要自己封装一个扩展类(eg:简单封装)【附录有】

附录:

# #输出+类型转换
# user_num1=input("输入第一个数:")
# user_num2=input("输入第二个数:")

# print("两数之和:%d"%(int(user_num1)+int(user_num2)))

# # ------------------------------------------------------------

# #字符串拼接
# user_name=input("输入昵称:")
# user_pass=input("输入密码:")
# user_url="192.168.1.121"

# #拼接输出方式一:
# print("ftp://"+user_name+":"+user_pass+"@"+user_url)

# #拼接输出方式二:
# print("ftp://%s:%s@%s"%(user_name,user_pass,user_url))

# # -------------------------------------------------------------

# # 字符串遍历、下标、切片
# user_str="七大姑曰:工作了吗?八大姨问:买房了吗?异性说:结婚了吗?"

# #遍历
# for item in user_str:
#     print(item,end=" ")

# #长度:len(user_str)
# print(len(user_str))

# #第一个元素:user_str[0]
# print(user_str[0])

# #最后一个元素:user_str[-1]
# print(user_str[-1])
# print(user_str[len(user_str)-1])#其他编程语言写法

# #倒数第二个元素:user_str[-2]
# print(user_str[-2])

# # -------------------------------------------------------------

# 切片:[start_index:end_index:step] (end_index取不到)
# eg:str[1:4] 取str[1]、str[2]、str[3]
# eg:str[2:] 取下标为2开始到最后的元素
# eg:str[2:-1] 取下标为2~到倒数第二个元素(end_index取不到)
# eg:str[1:6:2] 隔着取~str[1]、str[3]、str[5](案例会详细说)
# eg:str[::-1] 逆向输出(案例会详细说,)

it_str="我爱编程,编程爱它,它是程序,程序是谁?"

#eg:取“编程爱它” it_str[5:9]
print(it_str[5:9])
print(it_str[5:-11]) #end_index用-xx也一样
print(it_str[-15:-11])#start_index用-xx也可以

#eg:取“编程爱它,它是程序,程序是谁?” it_str[5:]
print(it_str[5:])#不写默认取到最后一个

#eg:一个隔一个跳着取("我编,程它它程,序谁") it_str[0::2]
print(it_str[0::2])#step=△index(eg:0,1,2,3。这里的step=> 2-0 => 间隔1)

#eg:倒序输出 it_str[::-1]
# end_index不写默认是取到最后一个,是正取(从左往右)还是逆取(从右往左),就看step是正是负
print(it_str[::-1])
print(it_str[-1::-1])#等价于上一个

# # -------------------------------------------------------------
View Code
test_str="ABCDabcdefacddbdf"

# -------------------------------------------------------------

# # 查找:find,rfind,index,rindex
# # xxx.find(str, start, end)
# print(test_str.find("cd"))#从左往右
# print(test_str.rfind("cd"))#从右往左
# print(test_str.find("dnt"))#find和rfind找不到就返回-1

# # index和rindex用法和find一样,只是找不到会报错(以后用find系即可)
# # print(test_str.index("dnt"))

# # -------------------------------------------------------------

# # 计数:count
# # xxx.count(str, start, end)
# print(test_str.count("a"))

# # -------------------------------------------------------------

# # 替换:replace
# # xxx.replace(str1, str2, count_num)
# print(test_str)
# print(test_str.replace("b","B"))#并没有改变原字符串,只是生成了一个新的字符串
# print(test_str)

# # replace可以指定替换几次
# print(test_str.replace("b","B",1))#ABCDaBcdefacddbdf

# # -------------------------------------------------------------

# 分割:split(按指定字符分割),splitlines(按行分割),,partition(以str分割成三部分,str前,str和str后),rpartition
# test_list=test_str.split("a")#a有两个,按照a分割,那么会分成三段,返回类型是列表(List),并且返回结果中没有a
# print(test_list)

# test_input="hi my name is dnt"
# print(test_input.split(" ")) #返回列表格式(后面会说)['hi', 'my', 'name', 'is', 'dnt']
# print(test_input.split(" ",3))#在第三个空格处切片,后面的不管了

# # 按行分割,返回类型为List
# test_line_str="abc\nbca\ncab\n"
# print(test_line_str.splitlines())#['abc', 'bca', 'cab']
# print(test_line_str.split("\n"))#看出区别了吧:['abc', 'bca', 'cab', '']

# # 没看出来就再来个案例
# test_line_str2="abc\nbca\ncab\nLLL"
# print(test_line_str2.splitlines())#['abc', 'bca', 'cab', 'LLL']
# print(test_line_str2.split("\n"))#再提示一下,最后不是\n就和上面一样效果

# 扩展:
# print("hi my name is dnt\t\n  m\n\t\n".split())#split(),默认按空字符切割(空格、\t、\n等等,不用担心返回'')

# #partition,返回是元祖类型(后面会说的),方式和find一样,找到第一个匹配的就罢工了
# print(test_str.partition("cd"))#('ABCDab', 'cd', 'efacddbdf')
# print(test_str.rpartition("cd"))#('ABCDabcdefa', 'cd', 'dbdf')
# print(test_str.partition("感觉自己萌萌哒"))#没找到:('ABCDabcdefacddbdf', '', '')

# # -------------------------------------------------------------

# # 连接:join
# # separat.join(xxx)
# # 错误用法:xxx.join("-")
# print("-".join(test_list))

# # -------------------------------------------------------------

# # 头尾判断:startswith(以。。。开头),endswith(以。。。结尾)
# # test_str.startswith(以。。。开头)
# start_end_str="http://www.baidu.net"
# print(start_end_str.startswith("https://") or start_end_str.startswith("http://"))
# print(start_end_str.endswith(".com"))
# # -------------------------------------------------------------

# # 大小写系:lower(字符串转换为小写),upper(字符串转换为大写),title(单词首字母大写),capitalize(第一个字符大写,其他变小写)
# print(test_str)
# print(test_str.upper())#ABCDABCDEFACDDBDF
# print(test_str.lower())#abcdabcdefacddbdf
# print(test_str.capitalize())#第一个字符大写,其他变小写

# # -------------------------------------------------------------

# # 格式系列:lstrip(去除左边空格),rstrip(去除右边空格),strip(去除两边空格),ljust,rjust,center
# strip_str=" I Have a Dream "
# print(strip_str.strip()+"|")#我加 | 是为了看清后面空格,没有别的用处
# print(strip_str.lstrip()+"|")
# print(strip_str.rstrip()+"|")

# #这个就是格式化输出,就不讲了
# print(test_str.ljust(50))
# print(test_str.rjust(50))
# print(test_str.center(50))
# # -------------------------------------------------------------

# 验证系列:isalpha(是否是纯字母),isalnum(是否是数字|字母),isdigit(是否是纯数字),isspace(是否是纯空格)

# test_str2="Abcd123"
# test_str3="123456"
# test_str4="  \t"
# test_str5="  \t \n " #isspace() ==>true
# 一张图搞定,其他的自己去试一试吧
# test_str.isalpha()
# test_str.isalnum()
# test_str.isdigit()
# test_str.isspace()
View Code

简单封装:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

public static partial class ValidationHelper
{
    #region 常用验证

    #region 集合系列
    /// <summary>
    /// 判断集合是否有数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <returns></returns>
    public static bool ExistsData<T>(this IEnumerable<T> list)
    {
        bool b = false;
        if (list != null && list.Count() > 0)
        {
            b = true;
        }
        return b;
    } 
    #endregion

    #region Null判断系列
    /// <summary>
    /// 判断是否为空或Null
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsNullOrWhiteSpace(this string objStr)
    {
        if (string.IsNullOrWhiteSpace(objStr))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 判断类型是否为可空类型
    /// </summary>
    /// <param name="theType"></param>
    /// <returns></returns>
    public static bool IsNullableType(Type theType)
    {
        return (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
    }
    #endregion

    #region 数字字符串检查
    /// <summary>
    /// 是否数字字符串(包括小数)
    /// </summary>
    /// <param name="objStr">输入字符串</param>
    /// <returns></returns>
    public static bool IsNumber(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"^\d+(\.\d+)?$");
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 是否是浮点数
    /// </summary>
    /// <param name="objStr">输入字符串</param>
    /// <returns></returns>
    public static bool IsDecimal(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"^(-?\d+)(\.\d+)?$");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #endregion

    #region 业务常用

    #region 中文检测
    /// <summary>
    /// 检测是否有中文字符
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsZhCN(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, "[\u4e00-\u9fa5]");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region 邮箱验证
    /// <summary>
    /// 判断邮箱地址是否正确
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsEmail(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region IP系列验证
    /// <summary>
    /// 是否为ip
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsIP(this string objStr)
    {
        return Regex.IsMatch(objStr, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
    }

    /// <summary>  
    /// 判断输入的字符串是否是表示一个IP地址  
    /// </summary>  
    /// <param name="objStr">被比较的字符串</param>  
    /// <returns>是IP地址则为True</returns>  
    public static bool IsIPv4(this string objStr)
    {
        string[] IPs = objStr.Split('.');
        for (int i = 0; i < IPs.Length; i++)
        {
            if (!Regex.IsMatch(IPs[i], @"^\d+$"))
            {
                return false;
            }
            if (Convert.ToUInt16(IPs[i]) > 255)
            {
                return false;
            }
        }
        return true;
    }

    /// <summary>
    /// 判断输入的字符串是否是合法的IPV6 地址  
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static bool IsIPV6(string input)
    {
        string temp = input;
        string[] strs = temp.Split(':');
        if (strs.Length > 8)
        {
            return false;
        }
        int count = input.GetStrCount("::");
        if (count > 1)
        {
            return false;
        }
        else if (count == 0)
        {
            return Regex.IsMatch(input, @"^([\da-f]{1,4}:){7}[\da-f]{1,4}$");
        }
        else
        {
            return Regex.IsMatch(input, @"^([\da-f]{1,4}:){0,5}::([\da-f]{1,4}:){0,5}[\da-f]{1,4}$");
        }
    }
    #endregion

    #region 网址系列验证
    /// <summary>
    /// 验证网址是否正确(http:或者https:)【后期添加 // 的情况】
    /// </summary>
    /// <param name="objStr">地址</param>
    /// <returns></returns>
    public static bool IsWebUrl(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?|https://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 判断输入的字符串是否是一个超链接  
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsURL(this string objStr)
    {
        string pattern = @"^[a-zA-Z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$";
        return Regex.IsMatch(objStr, pattern);
    }
    #endregion

    #region 邮政编码验证
    /// <summary>
    /// 验证邮政编码是否正确
    /// </summary>
    /// <param name="objStr">输入字符串</param>
    /// <returns></returns>
    public static bool IsZipCode(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"\d{6}");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region 电话+手机验证
    /// <summary>
    /// 验证手机号是否正确
    /// </summary>
    /// <param name="objStr">手机号</param>
    /// <returns></returns>
    public static bool IsMobile(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"^13[0-9]{9}|15[012356789][0-9]{8}|18[0123456789][0-9]{8}|147[0-9]{8}$");
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 匹配3位或4位区号的电话号码,其中区号可以用小括号括起来,也可以不用,区号与本地号间可以用连字号或空格间隔,也可以没有间隔   
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsPhone(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, "^\\(0\\d{2}\\)[- ]?\\d{8}$|^0\\d{2}[- ]?\\d{8}$|^\\(0\\d{3}\\)[- ]?\\d{7}$|^0\\d{3}[- ]?\\d{7}$");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region 字母或数字验证
    /// <summary>
    /// 是否只是字母或数字
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsAbcOr123(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"^[0-9a-zA-Z\$]+$");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #endregion
}
View Code

  说这么多基本上差不多完了,下次列表+字典+元组就一起讲了啊~ 

猜你喜欢

转载自www.cnblogs.com/dotnetcrazy/p/9114691.html